conf.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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. "fmt"
  7. "net/mail"
  8. "net/url"
  9. "os"
  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/redis"
  17. "github.com/gogs/go-libravatar"
  18. "github.com/mcuadros/go-version"
  19. "github.com/pkg/errors"
  20. "gopkg.in/ini.v1"
  21. log "unknwon.dev/clog/v2"
  22. "gogs.io/gogs/internal/assets/conf"
  23. "gogs.io/gogs/internal/osutil"
  24. )
  25. func init() {
  26. // Initialize the primary logger until logging service is up.
  27. err := log.NewConsole()
  28. if err != nil {
  29. panic("init console logger: " + err.Error())
  30. }
  31. }
  32. // Asset is a wrapper for getting conf assets.
  33. func Asset(name string) ([]byte, error) {
  34. return conf.Asset(name)
  35. }
  36. // AssetDir is a wrapper for getting conf assets.
  37. func AssetDir(name string) ([]string, error) {
  38. return conf.AssetDir(name)
  39. }
  40. // MustAsset is a wrapper for getting conf assets.
  41. func MustAsset(name string) []byte {
  42. return conf.MustAsset(name)
  43. }
  44. // File is the configuration object.
  45. var File *ini.File
  46. // Init initializes configuration from conf assets and given custom configuration file.
  47. // If `customConf` is empty, it falls back to default location, i.e. "<WORK DIR>/custom".
  48. // It is safe to call this function multiple times with desired `customConf`, but it is
  49. // not concurrent safe.
  50. //
  51. // NOTE: The order of loading configuration sections matters as one may depend on another.
  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. if customConf == "" {
  64. customConf = filepath.Join(CustomDir(), "conf", "app.ini")
  65. } else {
  66. customConf, err = filepath.Abs(customConf)
  67. if err != nil {
  68. return errors.Wrap(err, "get absolute path")
  69. }
  70. }
  71. CustomConf = customConf
  72. if osutil.IsFile(customConf) {
  73. if err = File.Append(customConf); err != nil {
  74. return errors.Wrapf(err, "append %q", customConf)
  75. }
  76. } else {
  77. log.Warn("Custom config %q not found. Ignore this warning if you're running for the first time", customConf)
  78. }
  79. if err = File.Section(ini.DefaultSection).MapTo(&App); err != nil {
  80. return errors.Wrap(err, "mapping default section")
  81. }
  82. // ***************************
  83. // ----- Server settings -----
  84. // ***************************
  85. if err = File.Section("server").MapTo(&Server); err != nil {
  86. return errors.Wrap(err, "mapping [server] section")
  87. }
  88. Server.AppDataPath = ensureAbs(Server.AppDataPath)
  89. if !strings.HasSuffix(Server.ExternalURL, "/") {
  90. Server.ExternalURL += "/"
  91. }
  92. Server.URL, err = url.Parse(Server.ExternalURL)
  93. if err != nil {
  94. return errors.Wrapf(err, "parse '[server] EXTERNAL_URL' %q", err)
  95. }
  96. // Subpath should start with '/' and end without '/', i.e. '/{subpath}'.
  97. Server.Subpath = strings.TrimRight(Server.URL.Path, "/")
  98. Server.SubpathDepth = strings.Count(Server.Subpath, "/")
  99. unixSocketMode, err := strconv.ParseUint(Server.UnixSocketPermission, 8, 32)
  100. if err != nil {
  101. return errors.Wrapf(err, "parse '[server] UNIX_SOCKET_PERMISSION' %q", Server.UnixSocketPermission)
  102. }
  103. if unixSocketMode > 0777 {
  104. unixSocketMode = 0666
  105. }
  106. Server.UnixSocketMode = os.FileMode(unixSocketMode)
  107. // ************************
  108. // ----- SSH settings -----
  109. // ************************
  110. SSH.RootPath = filepath.Join(HomeDir(), ".ssh")
  111. SSH.KeyTestPath = os.TempDir()
  112. if err = File.Section("server").MapTo(&SSH); err != nil {
  113. return errors.Wrap(err, "mapping SSH settings from [server] section")
  114. }
  115. SSH.RootPath = ensureAbs(SSH.RootPath)
  116. SSH.KeyTestPath = ensureAbs(SSH.KeyTestPath)
  117. if !SSH.Disabled {
  118. if !SSH.StartBuiltinServer {
  119. if err := os.MkdirAll(SSH.RootPath, 0700); err != nil {
  120. return errors.Wrap(err, "create SSH root directory")
  121. } else if err = os.MkdirAll(SSH.KeyTestPath, 0644); err != nil {
  122. return errors.Wrap(err, "create SSH key test directory")
  123. }
  124. } else {
  125. SSH.RewriteAuthorizedKeysAtStart = false
  126. }
  127. // Check if server is eligible for minimum key size check when user choose to enable.
  128. // Windows server and OpenSSH version lower than 5.1 are forced to be disabled because
  129. // the "ssh-keygen" in Windows does not print key type.
  130. // See https://github.com/gogs/gogs/issues/4507.
  131. if SSH.MinimumKeySizeCheck {
  132. sshVersion, err := openSSHVersion()
  133. if err != nil {
  134. return errors.Wrap(err, "get OpenSSH version")
  135. }
  136. if IsWindowsRuntime() || version.Compare(sshVersion, "5.1", "<") {
  137. log.Warn(`SSH minimum key size check is forced to be disabled because server is not eligible:
  138. 1. Windows server
  139. 2. OpenSSH version is lower than 5.1`)
  140. } else {
  141. SSH.MinimumKeySizes = map[string]int{}
  142. for _, key := range File.Section("ssh.minimum_key_sizes").Keys() {
  143. if key.MustInt() != -1 {
  144. SSH.MinimumKeySizes[strings.ToLower(key.Name())] = key.MustInt()
  145. }
  146. }
  147. }
  148. }
  149. }
  150. // *******************************
  151. // ----- Repository settings -----
  152. // *******************************
  153. Repository.Root = filepath.Join(HomeDir(), "gogs-repositories")
  154. if err = File.Section("repository").MapTo(&Repository); err != nil {
  155. return errors.Wrap(err, "mapping [repository] section")
  156. }
  157. Repository.Root = ensureAbs(Repository.Root)
  158. Repository.Upload.TempPath = ensureAbs(Repository.Upload.TempPath)
  159. // *****************************
  160. // ----- Database settings -----
  161. // *****************************
  162. if err = File.Section("database").MapTo(&Database); err != nil {
  163. return errors.Wrap(err, "mapping [database] section")
  164. }
  165. Database.Path = ensureAbs(Database.Path)
  166. // *****************************
  167. // ----- Security settings -----
  168. // *****************************
  169. if err = File.Section("security").MapTo(&Security); err != nil {
  170. return errors.Wrap(err, "mapping [security] section")
  171. }
  172. // Check run user when the install is locked.
  173. if Security.InstallLock {
  174. currentUser, match := CheckRunUser(App.RunUser)
  175. if !match {
  176. return fmt.Errorf("user configured to run Gogs is %q, but the current user is %q", App.RunUser, currentUser)
  177. }
  178. }
  179. // **************************
  180. // ----- Email settings -----
  181. // **************************
  182. if err = File.Section("email").MapTo(&Email); err != nil {
  183. return errors.Wrap(err, "mapping [email] section")
  184. }
  185. // LEGACY [0.13]: In case there are values with old section name.
  186. if err = File.Section("mailer").MapTo(&Email); err != nil {
  187. return errors.Wrap(err, "mapping [mailer] section")
  188. }
  189. if Email.Enabled {
  190. if Email.From == "" {
  191. Email.From = Email.User
  192. }
  193. parsed, err := mail.ParseAddress(Email.From)
  194. if err != nil {
  195. return errors.Wrapf(err, "parse mail address %q", Email.From)
  196. }
  197. Email.FromEmail = parsed.Address
  198. }
  199. // ***********************************
  200. // ----- Authentication settings -----
  201. // ***********************************
  202. if err = File.Section("auth").MapTo(&Auth); err != nil {
  203. return errors.Wrap(err, "mapping [auth] section")
  204. }
  205. // LEGACY [0.13]: In case there are values with old section name.
  206. if err = File.Section("service").MapTo(&Auth); err != nil {
  207. return errors.Wrap(err, "mapping [service] section")
  208. }
  209. // *************************
  210. // ----- User settings -----
  211. // *************************
  212. if err = File.Section("user").MapTo(&User); err != nil {
  213. return errors.Wrap(err, "mapping [user] section")
  214. }
  215. // ****************************
  216. // ----- Session settings -----
  217. // ****************************
  218. if err = File.Section("session").MapTo(&Session); err != nil {
  219. return errors.Wrap(err, "mapping [session] section")
  220. }
  221. // *******************************
  222. // ----- Attachment settings -----
  223. // *******************************
  224. if err = File.Section("attachment").MapTo(&Attachment); err != nil {
  225. return errors.Wrap(err, "mapping [attachment] section")
  226. }
  227. Attachment.Path = ensureAbs(Attachment.Path)
  228. // *************************
  229. // ----- Time settings -----
  230. // *************************
  231. if err = File.Section("time").MapTo(&Time); err != nil {
  232. return errors.Wrap(err, "mapping [time] section")
  233. }
  234. Time.FormatLayout = map[string]string{
  235. "ANSIC": time.ANSIC,
  236. "UnixDate": time.UnixDate,
  237. "RubyDate": time.RubyDate,
  238. "RFC822": time.RFC822,
  239. "RFC822Z": time.RFC822Z,
  240. "RFC850": time.RFC850,
  241. "RFC1123": time.RFC1123,
  242. "RFC1123Z": time.RFC1123Z,
  243. "RFC3339": time.RFC3339,
  244. "RFC3339Nano": time.RFC3339Nano,
  245. "Kitchen": time.Kitchen,
  246. "Stamp": time.Stamp,
  247. "StampMilli": time.StampMilli,
  248. "StampMicro": time.StampMicro,
  249. "StampNano": time.StampNano,
  250. }[Time.Format]
  251. if Time.FormatLayout == "" {
  252. return fmt.Errorf("unrecognized '[time] FORMAT': %s", Time.Format)
  253. }
  254. // ****************************
  255. // ----- Picture settings -----
  256. // ****************************
  257. if err = File.Section("picture").MapTo(&Picture); err != nil {
  258. return errors.Wrap(err, "mapping [picture] section")
  259. }
  260. Picture.AvatarUploadPath = ensureAbs(Picture.AvatarUploadPath)
  261. Picture.RepositoryAvatarUploadPath = ensureAbs(Picture.RepositoryAvatarUploadPath)
  262. switch Picture.GravatarSource {
  263. case "gravatar":
  264. Picture.GravatarSource = "https://secure.gravatar.com/avatar/"
  265. case "libravatar":
  266. Picture.GravatarSource = "https://seccdn.libravatar.org/avatar/"
  267. }
  268. if Server.OfflineMode {
  269. Picture.DisableGravatar = true
  270. Picture.EnableFederatedAvatar = false
  271. }
  272. if Picture.DisableGravatar {
  273. Picture.EnableFederatedAvatar = false
  274. }
  275. if Picture.EnableFederatedAvatar {
  276. gravatarURL, err := url.Parse(Picture.GravatarSource)
  277. if err != nil {
  278. return errors.Wrapf(err, "parse Gravatar source %q", Picture.GravatarSource)
  279. }
  280. Picture.LibravatarService = libravatar.New()
  281. if gravatarURL.Scheme == "https" {
  282. Picture.LibravatarService.SetUseHTTPS(true)
  283. Picture.LibravatarService.SetSecureFallbackHost(gravatarURL.Host)
  284. } else {
  285. Picture.LibravatarService.SetUseHTTPS(false)
  286. Picture.LibravatarService.SetFallbackHost(gravatarURL.Host)
  287. }
  288. }
  289. // ***************************
  290. // ----- Mirror settings -----
  291. // ***************************
  292. if err = File.Section("mirror").MapTo(&Mirror); err != nil {
  293. return errors.Wrap(err, "mapping [mirror] section")
  294. }
  295. if Mirror.DefaultInterval <= 0 {
  296. Mirror.DefaultInterval = 8
  297. }
  298. // *************************
  299. // ----- I18n settings -----
  300. // *************************
  301. I18n = new(i18nConf)
  302. if err = File.Section("i18n").MapTo(I18n); err != nil {
  303. return errors.Wrap(err, "mapping [i18n] section")
  304. }
  305. I18n.dateLangs = File.Section("i18n.datelang").KeysHash()
  306. handleDeprecated()
  307. if err = File.Section("cache").MapTo(&Cache); err != nil {
  308. return errors.Wrap(err, "mapping [cache] section")
  309. } else if err = File.Section("http").MapTo(&HTTP); err != nil {
  310. return errors.Wrap(err, "mapping [http] section")
  311. } else if err = File.Section("release").MapTo(&Release); err != nil {
  312. return errors.Wrap(err, "mapping [release] section")
  313. } else if err = File.Section("webhook").MapTo(&Webhook); err != nil {
  314. return errors.Wrap(err, "mapping [webhook] section")
  315. } else if err = File.Section("markdown").MapTo(&Markdown); err != nil {
  316. return errors.Wrap(err, "mapping [markdown] section")
  317. } else if err = File.Section("smartypants").MapTo(&Smartypants); err != nil {
  318. return errors.Wrap(err, "mapping [smartypants] section")
  319. } else if err = File.Section("admin").MapTo(&Admin); err != nil {
  320. return errors.Wrap(err, "mapping [admin] section")
  321. } else if err = File.Section("cron").MapTo(&Cron); err != nil {
  322. return errors.Wrap(err, "mapping [cron] section")
  323. } else if err = File.Section("git").MapTo(&Git); err != nil {
  324. return errors.Wrap(err, "mapping [git] section")
  325. } else if err = File.Section("api").MapTo(&API); err != nil {
  326. return errors.Wrap(err, "mapping [api] section")
  327. } else if err = File.Section("ui").MapTo(&UI); err != nil {
  328. return errors.Wrap(err, "mapping [ui] section")
  329. } else if err = File.Section("prometheus").MapTo(&Prometheus); err != nil {
  330. return errors.Wrap(err, "mapping [prometheus] section")
  331. } else if err = File.Section("other").MapTo(&Other); err != nil {
  332. return errors.Wrap(err, "mapping [other] section")
  333. }
  334. HasRobotsTxt = osutil.IsFile(filepath.Join(CustomDir(), "robots.txt"))
  335. return nil
  336. }
  337. // MustInit panics if configuration initialization failed.
  338. func MustInit(customConf string) {
  339. err := Init(customConf)
  340. if err != nil {
  341. panic(err)
  342. }
  343. }