conf.go 12 KB

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