conf.go 12 KB

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