conf.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  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/pkg/errors"
  19. "gopkg.in/ini.v1"
  20. log "unknwon.dev/clog/v2"
  21. "gogs.io/gogs/internal/assets/conf"
  22. "gogs.io/gogs/internal/osutil"
  23. "gogs.io/gogs/internal/semverutil"
  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 warnings.
  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() || semverutil.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. if Email.Enabled {
  186. if Email.From == "" {
  187. Email.From = Email.User
  188. }
  189. parsed, err := mail.ParseAddress(Email.From)
  190. if err != nil {
  191. return errors.Wrapf(err, "parse mail address %q", Email.From)
  192. }
  193. Email.FromEmail = parsed.Address
  194. }
  195. // ***********************************
  196. // ----- Authentication settings -----
  197. // ***********************************
  198. if err = File.Section("auth").MapTo(&Auth); err != nil {
  199. return errors.Wrap(err, "mapping [auth] section")
  200. }
  201. // *************************
  202. // ----- User settings -----
  203. // *************************
  204. if err = File.Section("user").MapTo(&User); err != nil {
  205. return errors.Wrap(err, "mapping [user] section")
  206. }
  207. // ****************************
  208. // ----- Session settings -----
  209. // ****************************
  210. if err = File.Section("session").MapTo(&Session); err != nil {
  211. return errors.Wrap(err, "mapping [session] section")
  212. }
  213. // *******************************
  214. // ----- Attachment settings -----
  215. // *******************************
  216. if err = File.Section("attachment").MapTo(&Attachment); err != nil {
  217. return errors.Wrap(err, "mapping [attachment] section")
  218. }
  219. Attachment.Path = ensureAbs(Attachment.Path)
  220. // *************************
  221. // ----- Time settings -----
  222. // *************************
  223. if err = File.Section("time").MapTo(&Time); err != nil {
  224. return errors.Wrap(err, "mapping [time] section")
  225. }
  226. Time.FormatLayout = map[string]string{
  227. "ANSIC": time.ANSIC,
  228. "UnixDate": time.UnixDate,
  229. "RubyDate": time.RubyDate,
  230. "RFC822": time.RFC822,
  231. "RFC822Z": time.RFC822Z,
  232. "RFC850": time.RFC850,
  233. "RFC1123": time.RFC1123,
  234. "RFC1123Z": time.RFC1123Z,
  235. "RFC3339": time.RFC3339,
  236. "RFC3339Nano": time.RFC3339Nano,
  237. "Kitchen": time.Kitchen,
  238. "Stamp": time.Stamp,
  239. "StampMilli": time.StampMilli,
  240. "StampMicro": time.StampMicro,
  241. "StampNano": time.StampNano,
  242. }[Time.Format]
  243. if Time.FormatLayout == "" {
  244. Time.FormatLayout = time.RFC3339
  245. }
  246. // ****************************
  247. // ----- Picture settings -----
  248. // ****************************
  249. if err = File.Section("picture").MapTo(&Picture); err != nil {
  250. return errors.Wrap(err, "mapping [picture] section")
  251. }
  252. Picture.AvatarUploadPath = ensureAbs(Picture.AvatarUploadPath)
  253. Picture.RepositoryAvatarUploadPath = ensureAbs(Picture.RepositoryAvatarUploadPath)
  254. switch Picture.GravatarSource {
  255. case "gravatar":
  256. Picture.GravatarSource = "https://secure.gravatar.com/avatar/"
  257. case "libravatar":
  258. Picture.GravatarSource = "https://seccdn.libravatar.org/avatar/"
  259. }
  260. if Server.OfflineMode {
  261. Picture.DisableGravatar = true
  262. Picture.EnableFederatedAvatar = false
  263. }
  264. if Picture.DisableGravatar {
  265. Picture.EnableFederatedAvatar = false
  266. }
  267. if Picture.EnableFederatedAvatar {
  268. gravatarURL, err := url.Parse(Picture.GravatarSource)
  269. if err != nil {
  270. return errors.Wrapf(err, "parse Gravatar source %q", Picture.GravatarSource)
  271. }
  272. Picture.LibravatarService = libravatar.New()
  273. if gravatarURL.Scheme == "https" {
  274. Picture.LibravatarService.SetUseHTTPS(true)
  275. Picture.LibravatarService.SetSecureFallbackHost(gravatarURL.Host)
  276. } else {
  277. Picture.LibravatarService.SetUseHTTPS(false)
  278. Picture.LibravatarService.SetFallbackHost(gravatarURL.Host)
  279. }
  280. }
  281. // ***************************
  282. // ----- Mirror settings -----
  283. // ***************************
  284. if err = File.Section("mirror").MapTo(&Mirror); err != nil {
  285. return errors.Wrap(err, "mapping [mirror] section")
  286. }
  287. if Mirror.DefaultInterval <= 0 {
  288. Mirror.DefaultInterval = 8
  289. }
  290. // *************************
  291. // ----- I18n settings -----
  292. // *************************
  293. I18n = new(i18nConf)
  294. if err = File.Section("i18n").MapTo(I18n); err != nil {
  295. return errors.Wrap(err, "mapping [i18n] section")
  296. }
  297. I18n.dateLangs = File.Section("i18n.datelang").KeysHash()
  298. // *************************
  299. // ----- LFS settings -----
  300. // *************************
  301. if err = File.Section("lfs").MapTo(&LFS); err != nil {
  302. return errors.Wrap(err, "mapping [lfs] section")
  303. }
  304. LFS.ObjectsPath = ensureAbs(LFS.ObjectsPath)
  305. handleDeprecated()
  306. if err = File.Section("cache").MapTo(&Cache); err != nil {
  307. return errors.Wrap(err, "mapping [cache] section")
  308. } else if err = File.Section("http").MapTo(&HTTP); err != nil {
  309. return errors.Wrap(err, "mapping [http] section")
  310. } else if err = File.Section("release").MapTo(&Release); err != nil {
  311. return errors.Wrap(err, "mapping [release] section")
  312. } else if err = File.Section("webhook").MapTo(&Webhook); err != nil {
  313. return errors.Wrap(err, "mapping [webhook] section")
  314. } else if err = File.Section("markdown").MapTo(&Markdown); err != nil {
  315. return errors.Wrap(err, "mapping [markdown] section")
  316. } else if err = File.Section("smartypants").MapTo(&Smartypants); err != nil {
  317. return errors.Wrap(err, "mapping [smartypants] section")
  318. } else if err = File.Section("admin").MapTo(&Admin); err != nil {
  319. return errors.Wrap(err, "mapping [admin] section")
  320. } else if err = File.Section("cron").MapTo(&Cron); err != nil {
  321. return errors.Wrap(err, "mapping [cron] section")
  322. } else if err = File.Section("git").MapTo(&Git); err != nil {
  323. return errors.Wrap(err, "mapping [git] section")
  324. } else if err = File.Section("api").MapTo(&API); err != nil {
  325. return errors.Wrap(err, "mapping [api] section")
  326. } else if err = File.Section("ui").MapTo(&UI); err != nil {
  327. return errors.Wrap(err, "mapping [ui] section")
  328. } else if err = File.Section("prometheus").MapTo(&Prometheus); err != nil {
  329. return errors.Wrap(err, "mapping [prometheus] section")
  330. } else if err = File.Section("other").MapTo(&Other); err != nil {
  331. return errors.Wrap(err, "mapping [other] section")
  332. }
  333. HasRobotsTxt = osutil.IsFile(filepath.Join(CustomDir(), "robots.txt"))
  334. return nil
  335. }
  336. // MustInit panics if configuration initialization failed.
  337. func MustInit(customConf string) {
  338. err := Init(customConf)
  339. if err != nil {
  340. panic(err)
  341. }
  342. }