conf.go 12 KB

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