conf.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830
  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. Server.AppDataPath = ensureAbs(Server.AppDataPath)
  88. if !strings.HasSuffix(Server.ExternalURL, "/") {
  89. Server.ExternalURL += "/"
  90. }
  91. Server.URL, err = url.Parse(Server.ExternalURL)
  92. if err != nil {
  93. return errors.Wrapf(err, "parse '[server] EXTERNAL_URL' %q", err)
  94. }
  95. // Subpath should start with '/' and end without '/', i.e. '/{subpath}'.
  96. Server.Subpath = strings.TrimRight(Server.URL.Path, "/")
  97. Server.SubpathDepth = strings.Count(Server.Subpath, "/")
  98. unixSocketMode, err := strconv.ParseUint(Server.UnixSocketPermission, 8, 32)
  99. if err != nil {
  100. return errors.Wrapf(err, "parse '[server] UNIX_SOCKET_PERMISSION' %q", Server.UnixSocketPermission)
  101. }
  102. if unixSocketMode > 0777 {
  103. unixSocketMode = 0666
  104. }
  105. Server.UnixSocketMode = os.FileMode(unixSocketMode)
  106. // ************************
  107. // ----- SSH settings -----
  108. // ************************
  109. SSH.RootPath = filepath.Join(HomeDir(), ".ssh")
  110. SSH.KeyTestPath = os.TempDir()
  111. if err = File.Section("server").MapTo(&SSH); err != nil {
  112. return errors.Wrap(err, "mapping SSH settings from [server] section")
  113. }
  114. SSH.RootPath = ensureAbs(SSH.RootPath)
  115. SSH.KeyTestPath = ensureAbs(SSH.KeyTestPath)
  116. if !SSH.Disabled {
  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. // *******************************
  150. // ----- Repository settings -----
  151. // *******************************
  152. Repository.Root = filepath.Join(HomeDir(), "gogs-repositories")
  153. if err = File.Section("repository").MapTo(&Repository); err != nil {
  154. return errors.Wrap(err, "mapping [repository] section")
  155. }
  156. Repository.Root = ensureAbs(Repository.Root)
  157. Repository.Upload.TempPath = ensureAbs(Repository.Upload.TempPath)
  158. // *******************************
  159. // ----- Database settings -----
  160. // *******************************
  161. if err = File.Section("database").MapTo(&Database); err != nil {
  162. return errors.Wrap(err, "mapping [database] section")
  163. }
  164. Database.Path = ensureAbs(Database.Path)
  165. handleDeprecated()
  166. // TODO
  167. sec := File.Section("security")
  168. InstallLock = sec.Key("INSTALL_LOCK").MustBool()
  169. SecretKey = sec.Key("SECRET_KEY").String()
  170. LoginRememberDays = sec.Key("LOGIN_REMEMBER_DAYS").MustInt()
  171. CookieUserName = sec.Key("COOKIE_USERNAME").String()
  172. CookieRememberName = sec.Key("COOKIE_REMEMBER_NAME").String()
  173. CookieSecure = sec.Key("COOKIE_SECURE").MustBool(false)
  174. ReverseProxyAuthUser = sec.Key("REVERSE_PROXY_AUTHENTICATION_USER").MustString("X-WEBAUTH-USER")
  175. EnableLoginStatusCookie = sec.Key("ENABLE_LOGIN_STATUS_COOKIE").MustBool(false)
  176. LoginStatusCookieName = sec.Key("LOGIN_STATUS_COOKIE_NAME").MustString("login_status")
  177. // Does not check run user when the install lock is off.
  178. if InstallLock {
  179. currentUser, match := IsRunUserMatchCurrentUser(App.RunUser)
  180. if !match {
  181. log.Fatal("The user configured to run Gogs is %q, but the current user is %q", App.RunUser, currentUser)
  182. }
  183. }
  184. sec = File.Section("attachment")
  185. AttachmentPath = sec.Key("PATH").MustString(filepath.Join(Server.AppDataPath, "attachments"))
  186. if !filepath.IsAbs(AttachmentPath) {
  187. AttachmentPath = path.Join(workDir, AttachmentPath)
  188. }
  189. AttachmentAllowedTypes = strings.Replace(sec.Key("ALLOWED_TYPES").MustString("image/jpeg,image/png"), "|", ",", -1)
  190. AttachmentMaxSize = sec.Key("MAX_SIZE").MustInt64(4)
  191. AttachmentMaxFiles = sec.Key("MAX_FILES").MustInt(5)
  192. AttachmentEnabled = sec.Key("ENABLED").MustBool(true)
  193. TimeFormat = map[string]string{
  194. "ANSIC": time.ANSIC,
  195. "UnixDate": time.UnixDate,
  196. "RubyDate": time.RubyDate,
  197. "RFC822": time.RFC822,
  198. "RFC822Z": time.RFC822Z,
  199. "RFC850": time.RFC850,
  200. "RFC1123": time.RFC1123,
  201. "RFC1123Z": time.RFC1123Z,
  202. "RFC3339": time.RFC3339,
  203. "RFC3339Nano": time.RFC3339Nano,
  204. "Kitchen": time.Kitchen,
  205. "Stamp": time.Stamp,
  206. "StampMilli": time.StampMilli,
  207. "StampMicro": time.StampMicro,
  208. "StampNano": time.StampNano,
  209. }[File.Section("time").Key("FORMAT").MustString("RFC1123")]
  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. // Webhook settings
  315. Webhook struct {
  316. Types []string
  317. QueueLength int
  318. DeliverTimeout int
  319. SkipTLSVerify bool `ini:"SKIP_TLS_VERIFY"`
  320. PagingNum int
  321. }
  322. // Release settigns
  323. Release struct {
  324. Attachment struct {
  325. Enabled bool
  326. TempPath string
  327. AllowedTypes []string `delim:"|"`
  328. MaxSize int64
  329. MaxFiles int
  330. } `ini:"-"`
  331. }
  332. // Markdown sttings
  333. Markdown struct {
  334. EnableHardLineBreak bool
  335. CustomURLSchemes []string `ini:"CUSTOM_URL_SCHEMES"`
  336. FileExtensions []string
  337. }
  338. // Smartypants settings
  339. Smartypants struct {
  340. Enabled bool
  341. Fractions bool
  342. Dashes bool
  343. LatexDashes bool
  344. AngledQuotes bool
  345. }
  346. // Admin settings
  347. Admin struct {
  348. DisableRegularOrgCreation bool
  349. }
  350. // Picture settings
  351. AvatarUploadPath string
  352. RepositoryAvatarUploadPath string
  353. GravatarSource string
  354. DisableGravatar bool
  355. EnableFederatedAvatar bool
  356. LibravatarService *libravatar.Libravatar
  357. // Log settings
  358. LogRootPath string
  359. LogModes []string
  360. LogConfigs []interface{}
  361. // Attachment settings
  362. AttachmentPath string
  363. AttachmentAllowedTypes string
  364. AttachmentMaxSize int64
  365. AttachmentMaxFiles int
  366. AttachmentEnabled bool
  367. // Time settings
  368. TimeFormat string
  369. // Cache settings
  370. CacheAdapter string
  371. CacheInterval int
  372. CacheConn string
  373. // Session settings
  374. SessionConfig session.Options
  375. CSRFCookieName string
  376. // Cron tasks
  377. Cron struct {
  378. UpdateMirror struct {
  379. Enabled bool
  380. RunAtStart bool
  381. Schedule string
  382. } `ini:"cron.update_mirrors"`
  383. RepoHealthCheck struct {
  384. Enabled bool
  385. RunAtStart bool
  386. Schedule string
  387. Timeout time.Duration
  388. Args []string `delim:" "`
  389. } `ini:"cron.repo_health_check"`
  390. CheckRepoStats struct {
  391. Enabled bool
  392. RunAtStart bool
  393. Schedule string
  394. } `ini:"cron.check_repo_stats"`
  395. RepoArchiveCleanup struct {
  396. Enabled bool
  397. RunAtStart bool
  398. Schedule string
  399. OlderThan time.Duration
  400. } `ini:"cron.repo_archive_cleanup"`
  401. }
  402. // Git settings
  403. Git struct {
  404. Version string `ini:"-"`
  405. DisableDiffHighlight bool
  406. MaxGitDiffLines int
  407. MaxGitDiffLineCharacters int
  408. MaxGitDiffFiles int
  409. GCArgs []string `ini:"GC_ARGS" delim:" "`
  410. Timeout struct {
  411. Migrate int
  412. Mirror int
  413. Clone int
  414. Pull int
  415. GC int `ini:"GC"`
  416. } `ini:"git.timeout"`
  417. }
  418. // Mirror settings
  419. Mirror struct {
  420. DefaultInterval int
  421. }
  422. // API settings
  423. API struct {
  424. MaxResponseItems int
  425. }
  426. // UI settings
  427. UI struct {
  428. ExplorePagingNum int
  429. IssuePagingNum int
  430. FeedMaxCommitNum int
  431. ThemeColorMetaTag string
  432. MaxDisplayFileSize int64
  433. Admin struct {
  434. UserPagingNum int
  435. RepoPagingNum int
  436. NoticePagingNum int
  437. OrgPagingNum int
  438. } `ini:"ui.admin"`
  439. User struct {
  440. RepoPagingNum int
  441. NewsFeedPagingNum int
  442. CommitsPagingNum int
  443. } `ini:"ui.user"`
  444. }
  445. // Prometheus settings
  446. Prometheus struct {
  447. Enabled bool
  448. EnableBasicAuth bool
  449. BasicAuthUsername string
  450. BasicAuthPassword string
  451. }
  452. // I18n settings
  453. Langs []string
  454. Names []string
  455. dateLangs map[string]string
  456. // Highlight settings are loaded in modules/template/hightlight.go
  457. // Other settings
  458. ShowFooterBranding bool
  459. ShowFooterTemplateLoadTime bool
  460. // Global setting objects
  461. HasRobotsTxt bool
  462. )
  463. // DateLang transforms standard language locale name to corresponding value in datetime plugin.
  464. func DateLang(lang string) string {
  465. name, ok := dateLangs[lang]
  466. if ok {
  467. return name
  468. }
  469. return "en"
  470. }
  471. // IsRunUserMatchCurrentUser returns false if configured run user does not match
  472. // actual user that runs the app. The first return value is the actual user name.
  473. // This check is ignored under Windows since SSH remote login is not the main
  474. // method to login on Windows.
  475. func IsRunUserMatchCurrentUser(runUser string) (string, bool) {
  476. if IsWindowsRuntime() {
  477. return "", true
  478. }
  479. currentUser := user.CurrentUsername()
  480. return currentUser, runUser == currentUser
  481. }
  482. // InitLogging initializes the logging service of the application.
  483. func InitLogging() {
  484. LogRootPath = File.Section("log").Key("ROOT_PATH").MustString(filepath.Join(WorkDir(), "log"))
  485. // Because we always create a console logger as the primary logger at init time,
  486. // we need to remove it in case the user doesn't configure to use it after the
  487. // logging service is initalized.
  488. hasConsole := false
  489. // Iterate over [log.*] sections to initialize individual logger.
  490. LogModes = strings.Split(File.Section("log").Key("MODE").MustString("console"), ",")
  491. LogConfigs = make([]interface{}, len(LogModes))
  492. levelMappings := map[string]log.Level{
  493. "trace": log.LevelTrace,
  494. "info": log.LevelInfo,
  495. "warn": log.LevelWarn,
  496. "error": log.LevelError,
  497. "fatal": log.LevelFatal,
  498. }
  499. type config struct {
  500. Buffer int64
  501. Config interface{}
  502. }
  503. for i, mode := range LogModes {
  504. mode = strings.ToLower(strings.TrimSpace(mode))
  505. secName := "log." + mode
  506. sec, err := File.GetSection(secName)
  507. if err != nil {
  508. log.Fatal("Missing configuration section [%s] for %q logger", secName, mode)
  509. return
  510. }
  511. level := levelMappings[sec.Key("LEVEL").MustString("trace")]
  512. buffer := sec.Key("BUFFER_LEN").MustInt64(100)
  513. c := new(config)
  514. switch mode {
  515. case log.DefaultConsoleName:
  516. hasConsole = true
  517. c = &config{
  518. Buffer: buffer,
  519. Config: log.ConsoleConfig{
  520. Level: level,
  521. },
  522. }
  523. err = log.NewConsole(c.Buffer, c.Config)
  524. case log.DefaultFileName:
  525. logPath := filepath.Join(LogRootPath, "gogs.log")
  526. logDir := filepath.Dir(logPath)
  527. err = os.MkdirAll(logDir, os.ModePerm)
  528. if err != nil {
  529. log.Fatal("Failed to create log directory %q: %v", logDir, err)
  530. return
  531. }
  532. c = &config{
  533. Buffer: buffer,
  534. Config: log.FileConfig{
  535. Level: level,
  536. Filename: logPath,
  537. FileRotationConfig: log.FileRotationConfig{
  538. Rotate: sec.Key("LOG_ROTATE").MustBool(true),
  539. Daily: sec.Key("DAILY_ROTATE").MustBool(true),
  540. MaxSize: 1 << uint(sec.Key("MAX_SIZE_SHIFT").MustInt(28)),
  541. MaxLines: sec.Key("MAX_LINES").MustInt64(1000000),
  542. MaxDays: sec.Key("MAX_DAYS").MustInt64(7),
  543. },
  544. },
  545. }
  546. err = log.NewFile(c.Buffer, c.Config)
  547. case log.DefaultSlackName:
  548. c = &config{
  549. Buffer: buffer,
  550. Config: log.SlackConfig{
  551. Level: level,
  552. URL: sec.Key("URL").String(),
  553. },
  554. }
  555. err = log.NewSlack(c.Buffer, c.Config)
  556. case log.DefaultDiscordName:
  557. c = &config{
  558. Buffer: buffer,
  559. Config: log.DiscordConfig{
  560. Level: level,
  561. URL: sec.Key("URL").String(),
  562. Username: sec.Key("USERNAME").String(),
  563. },
  564. }
  565. default:
  566. continue
  567. }
  568. if err != nil {
  569. log.Fatal("Failed to init %s logger: %v", mode, err)
  570. return
  571. }
  572. LogConfigs[i] = c
  573. log.Trace("Log mode: %s (%s)", strings.Title(mode), strings.Title(strings.ToLower(level.String())))
  574. }
  575. if !hasConsole {
  576. log.Remove(log.DefaultConsoleName)
  577. }
  578. }
  579. var Service struct {
  580. ActiveCodeLives int
  581. ResetPwdCodeLives int
  582. RegisterEmailConfirm bool
  583. DisableRegistration bool
  584. ShowRegistrationButton bool
  585. RequireSignInView bool
  586. EnableNotifyMail bool
  587. EnableReverseProxyAuth bool
  588. EnableReverseProxyAutoRegister bool
  589. EnableCaptcha bool
  590. }
  591. func newService() {
  592. sec := File.Section("service")
  593. Service.ActiveCodeLives = sec.Key("ACTIVE_CODE_LIVE_MINUTES").MustInt(180)
  594. Service.ResetPwdCodeLives = sec.Key("RESET_PASSWD_CODE_LIVE_MINUTES").MustInt(180)
  595. Service.DisableRegistration = sec.Key("DISABLE_REGISTRATION").MustBool()
  596. Service.ShowRegistrationButton = sec.Key("SHOW_REGISTRATION_BUTTON").MustBool(!Service.DisableRegistration)
  597. Service.RequireSignInView = sec.Key("REQUIRE_SIGNIN_VIEW").MustBool()
  598. Service.EnableReverseProxyAuth = sec.Key("ENABLE_REVERSE_PROXY_AUTHENTICATION").MustBool()
  599. Service.EnableReverseProxyAutoRegister = sec.Key("ENABLE_REVERSE_PROXY_AUTO_REGISTRATION").MustBool()
  600. Service.EnableCaptcha = sec.Key("ENABLE_CAPTCHA").MustBool()
  601. }
  602. func newCacheService() {
  603. CacheAdapter = File.Section("cache").Key("ADAPTER").In("memory", []string{"memory", "redis", "memcache"})
  604. switch CacheAdapter {
  605. case "memory":
  606. CacheInterval = File.Section("cache").Key("INTERVAL").MustInt(60)
  607. case "redis", "memcache":
  608. CacheConn = strings.Trim(File.Section("cache").Key("HOST").String(), "\" ")
  609. default:
  610. log.Fatal("Unrecognized cache adapter %q", CacheAdapter)
  611. return
  612. }
  613. log.Trace("Cache service is enabled")
  614. }
  615. func newSessionService() {
  616. SessionConfig.Provider = File.Section("session").Key("PROVIDER").In("memory",
  617. []string{"memory", "file", "redis", "mysql"})
  618. SessionConfig.ProviderConfig = strings.Trim(File.Section("session").Key("PROVIDER_CONFIG").String(), "\" ")
  619. SessionConfig.CookieName = File.Section("session").Key("COOKIE_NAME").MustString("i_like_gogs")
  620. SessionConfig.CookiePath = Server.Subpath
  621. SessionConfig.Secure = File.Section("session").Key("COOKIE_SECURE").MustBool()
  622. SessionConfig.Gclifetime = File.Section("session").Key("GC_INTERVAL_TIME").MustInt64(3600)
  623. SessionConfig.Maxlifetime = File.Section("session").Key("SESSION_LIFE_TIME").MustInt64(86400)
  624. CSRFCookieName = File.Section("session").Key("CSRF_COOKIE_NAME").MustString("_csrf")
  625. log.Trace("Session service is enabled")
  626. }
  627. // Mailer represents mail service.
  628. type Mailer struct {
  629. QueueLength int
  630. SubjectPrefix string
  631. Host string
  632. From string
  633. FromEmail string
  634. User, Passwd string
  635. DisableHelo bool
  636. HeloHostname string
  637. SkipVerify bool
  638. UseCertificate bool
  639. CertFile, KeyFile string
  640. UsePlainText bool
  641. AddPlainTextAlt bool
  642. }
  643. var (
  644. MailService *Mailer
  645. )
  646. // newMailService initializes mail service options from configuration.
  647. // No non-error log will be printed in hook mode.
  648. func newMailService() {
  649. sec := File.Section("mailer")
  650. if !sec.Key("ENABLED").MustBool() {
  651. return
  652. }
  653. MailService = &Mailer{
  654. QueueLength: sec.Key("SEND_BUFFER_LEN").MustInt(100),
  655. SubjectPrefix: sec.Key("SUBJECT_PREFIX").MustString("[" + App.BrandName + "] "),
  656. Host: sec.Key("HOST").String(),
  657. User: sec.Key("USER").String(),
  658. Passwd: sec.Key("PASSWD").String(),
  659. DisableHelo: sec.Key("DISABLE_HELO").MustBool(),
  660. HeloHostname: sec.Key("HELO_HOSTNAME").String(),
  661. SkipVerify: sec.Key("SKIP_VERIFY").MustBool(),
  662. UseCertificate: sec.Key("USE_CERTIFICATE").MustBool(),
  663. CertFile: sec.Key("CERT_FILE").String(),
  664. KeyFile: sec.Key("KEY_FILE").String(),
  665. UsePlainText: sec.Key("USE_PLAIN_TEXT").MustBool(),
  666. AddPlainTextAlt: sec.Key("ADD_PLAIN_TEXT_ALT").MustBool(),
  667. }
  668. MailService.From = sec.Key("FROM").MustString(MailService.User)
  669. if len(MailService.From) > 0 {
  670. parsed, err := mail.ParseAddress(MailService.From)
  671. if err != nil {
  672. log.Fatal("Failed to parse value %q for '[mailer] FROM': %v", MailService.From, err)
  673. return
  674. }
  675. MailService.FromEmail = parsed.Address
  676. }
  677. if HookMode {
  678. return
  679. }
  680. log.Trace("Mail service is enabled")
  681. }
  682. func newRegisterMailService() {
  683. if !File.Section("service").Key("REGISTER_EMAIL_CONFIRM").MustBool() {
  684. return
  685. } else if MailService == nil {
  686. log.Warn("Email confirmation is not enabled due to the mail service is not available")
  687. return
  688. }
  689. Service.RegisterEmailConfirm = true
  690. log.Trace("Email confirmation is enabled")
  691. }
  692. // newNotifyMailService initializes notification email service options from configuration.
  693. // No non-error log will be printed in hook mode.
  694. func newNotifyMailService() {
  695. if !File.Section("service").Key("ENABLE_NOTIFY_MAIL").MustBool() {
  696. return
  697. } else if MailService == nil {
  698. log.Warn("Email notification is not enabled due to the mail service is not available")
  699. return
  700. }
  701. Service.EnableNotifyMail = true
  702. if HookMode {
  703. return
  704. }
  705. log.Trace("Email notification is enabled")
  706. }
  707. func NewService() {
  708. newService()
  709. }
  710. func NewServices() {
  711. newService()
  712. newCacheService()
  713. newSessionService()
  714. newMailService()
  715. newRegisterMailService()
  716. newNotifyMailService()
  717. }
  718. // HookMode indicates whether program starts as Git server-side hook callback.
  719. var HookMode bool
  720. // NewPostReceiveHookServices initializes all services that are needed by
  721. // Git server-side post-receive hook callback.
  722. func NewPostReceiveHookServices() {
  723. HookMode = true
  724. newService()
  725. newMailService()
  726. newNotifyMailService()
  727. }