conf.go 12 KB

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