static.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. package conf
  2. import (
  3. "fmt"
  4. "net/url"
  5. "os"
  6. "time"
  7. "github.com/gogs/go-libravatar"
  8. "gopkg.in/ini.v1"
  9. "gogs.io/gogs/conf"
  10. )
  11. // ℹ️ README: This file contains static values that should only be set at initialization time.
  12. //
  13. // ⚠️ WARNING: After changing any options, do not forget to update template of
  14. // "/admin/config" page as well.
  15. // HasMinWinSvc is whether the application is built with Windows Service support.
  16. //
  17. // ⚠️ WARNING: should only be set by "internal/conf/static_minwinsvc.go".
  18. var HasMinWinSvc bool
  19. // Build time and commit information.
  20. //
  21. // ⚠️ WARNING: should only be set by "-ldflags".
  22. var (
  23. BuildTime string
  24. BuildCommit string
  25. )
  26. // CustomConf returns the absolute path of custom configuration file that is used.
  27. var CustomConf string
  28. var (
  29. // Security settings
  30. Security struct {
  31. InstallLock bool
  32. SecretKey string
  33. LoginRememberDays int
  34. CookieRememberName string
  35. CookieUsername string
  36. CookieSecure bool
  37. EnableLoginStatusCookie bool
  38. LoginStatusCookieName string
  39. LocalNetworkAllowlist []string `delim:","`
  40. }
  41. // Email settings
  42. Email struct {
  43. Enabled bool
  44. SubjectPrefix string
  45. Host string
  46. From string
  47. User string
  48. Password string
  49. HELOHostname string `ini:"HELO_HOSTNAME"`
  50. SkipVerify bool
  51. UseCertificate bool
  52. CertFile string
  53. KeyFile string
  54. UsePlainText bool
  55. AddPlainTextAlt bool
  56. // Derived from other static values
  57. FromEmail string `ini:"-"` // Parsed email address of From without person's name.
  58. }
  59. // User settings
  60. User struct {
  61. EnableEmailNotification bool
  62. }
  63. // Session settings
  64. Session struct {
  65. Provider string
  66. ProviderConfig string
  67. CookieName string
  68. CookieSecure bool
  69. GCInterval int64 `ini:"GC_INTERVAL"`
  70. MaxLifeTime int64
  71. CSRFCookieName string `ini:"CSRF_COOKIE_NAME"`
  72. }
  73. // Cache settings
  74. Cache struct {
  75. Adapter string
  76. Interval int
  77. Host string
  78. }
  79. // HTTP settings
  80. HTTP struct {
  81. AccessControlAllowOrigin string
  82. }
  83. // Attachment settings
  84. Attachment struct {
  85. Enabled bool
  86. Path string
  87. AllowedTypes []string `delim:"|"`
  88. MaxSize int64
  89. MaxFiles int
  90. }
  91. // Release settings
  92. Release struct {
  93. Attachment struct {
  94. Enabled bool
  95. AllowedTypes []string `delim:"|"`
  96. MaxSize int64
  97. MaxFiles int
  98. } `ini:"release.attachment"`
  99. }
  100. // Time settings
  101. Time struct {
  102. Format string
  103. // Derived from other static values
  104. FormatLayout string `ini:"-"` // Actual layout of the Format.
  105. }
  106. // Mirror settings
  107. Mirror struct {
  108. DefaultInterval int
  109. }
  110. // Webhook settings
  111. Webhook struct {
  112. Types []string
  113. DeliverTimeout int
  114. SkipTLSVerify bool `ini:"SKIP_TLS_VERIFY"`
  115. PagingNum int
  116. }
  117. // Markdown settings
  118. Markdown struct {
  119. EnableHardLineBreak bool
  120. CustomURLSchemes []string `ini:"CUSTOM_URL_SCHEMES"`
  121. FileExtensions []string
  122. }
  123. // Smartypants settings
  124. Smartypants struct {
  125. Enabled bool
  126. Fractions bool
  127. Dashes bool
  128. LatexDashes bool
  129. AngledQuotes bool
  130. }
  131. // Admin settings
  132. Admin struct {
  133. DisableRegularOrgCreation bool
  134. }
  135. // Cron tasks
  136. Cron struct {
  137. UpdateMirror struct {
  138. Enabled bool
  139. RunAtStart bool
  140. Schedule string
  141. } `ini:"cron.update_mirrors"`
  142. RepoHealthCheck struct {
  143. Enabled bool
  144. RunAtStart bool
  145. Schedule string
  146. Timeout time.Duration
  147. Args []string `delim:" "`
  148. } `ini:"cron.repo_health_check"`
  149. CheckRepoStats struct {
  150. Enabled bool
  151. RunAtStart bool
  152. Schedule string
  153. } `ini:"cron.check_repo_stats"`
  154. RepoArchiveCleanup struct {
  155. Enabled bool
  156. RunAtStart bool
  157. Schedule string
  158. OlderThan time.Duration
  159. } `ini:"cron.repo_archive_cleanup"`
  160. }
  161. // Git settings
  162. Git struct {
  163. // ⚠️ WARNING: Should only be set by "internal/db/repo.go".
  164. Version string `ini:"-"`
  165. DisableDiffHighlight bool
  166. MaxDiffFiles int `ini:"MAX_GIT_DIFF_FILES"`
  167. MaxDiffLines int `ini:"MAX_GIT_DIFF_LINES"`
  168. MaxDiffLineChars int `ini:"MAX_GIT_DIFF_LINE_CHARACTERS"`
  169. GCArgs []string `ini:"GC_ARGS" delim:" "`
  170. Timeout struct {
  171. Migrate int
  172. Mirror int
  173. Clone int
  174. Pull int
  175. Diff int
  176. GC int `ini:"GC"`
  177. } `ini:"git.timeout"`
  178. }
  179. // API settings
  180. API struct {
  181. MaxResponseItems int
  182. }
  183. // Prometheus settings
  184. Prometheus struct {
  185. Enabled bool
  186. EnableBasicAuth bool
  187. BasicAuthUsername string
  188. BasicAuthPassword string
  189. }
  190. // Other settings
  191. Other struct {
  192. ShowFooterBranding bool
  193. ShowFooterTemplateLoadTime bool
  194. }
  195. // Global setting
  196. HasRobotsTxt bool
  197. )
  198. type AppOpts struct {
  199. // ⚠️ WARNING: Should only be set by the main package (i.e. "cmd/gogs/main.go").
  200. Version string `ini:"-"`
  201. BrandName string
  202. RunUser string
  203. RunMode string
  204. }
  205. // Application settings
  206. var App AppOpts
  207. type AuthOpts struct {
  208. ActivateCodeLives int
  209. ResetPasswordCodeLives int
  210. RequireEmailConfirmation bool
  211. RequireSigninView bool
  212. DisableRegistration bool
  213. EnableRegistrationCaptcha bool
  214. EnableReverseProxyAuthentication bool
  215. EnableReverseProxyAutoRegistration bool
  216. ReverseProxyAuthenticationHeader string
  217. CustomLogoutURL string `ini:"CUSTOM_LOGOUT_URL"`
  218. }
  219. // Authentication settings
  220. var Auth AuthOpts
  221. type ServerOpts struct {
  222. ExternalURL string `ini:"EXTERNAL_URL"`
  223. Domain string
  224. Protocol string
  225. HTTPAddr string `ini:"HTTP_ADDR"`
  226. HTTPPort string `ini:"HTTP_PORT"`
  227. CertFile string
  228. KeyFile string
  229. TLSMinVersion string `ini:"TLS_MIN_VERSION"`
  230. UnixSocketPermission string
  231. LocalRootURL string `ini:"LOCAL_ROOT_URL"`
  232. OfflineMode bool
  233. DisableRouterLog bool
  234. EnableGzip bool
  235. AppDataPath string
  236. LoadAssetsFromDisk bool
  237. LandingURL string `ini:"LANDING_URL"`
  238. // Derived from other static values
  239. URL *url.URL `ini:"-"` // Parsed URL object of ExternalURL.
  240. Subpath string `ini:"-"` // Subpath found the ExternalURL. Should be empty when not found.
  241. SubpathDepth int `ini:"-"` // The number of slashes found in the Subpath.
  242. UnixSocketMode os.FileMode `ini:"-"` // Parsed file mode of UnixSocketPermission.
  243. }
  244. // Server settings
  245. var Server ServerOpts
  246. type SSHOpts struct {
  247. Disabled bool `ini:"DISABLE_SSH"`
  248. Domain string `ini:"SSH_DOMAIN"`
  249. Port int `ini:"SSH_PORT"`
  250. RootPath string `ini:"SSH_ROOT_PATH"`
  251. KeygenPath string `ini:"SSH_KEYGEN_PATH"`
  252. KeyTestPath string `ini:"SSH_KEY_TEST_PATH"`
  253. MinimumKeySizeCheck bool
  254. MinimumKeySizes map[string]int `ini:"-"` // Load from [ssh.minimum_key_sizes]
  255. RewriteAuthorizedKeysAtStart bool
  256. StartBuiltinServer bool `ini:"START_SSH_SERVER"`
  257. ListenHost string `ini:"SSH_LISTEN_HOST"`
  258. ListenPort int `ini:"SSH_LISTEN_PORT"`
  259. ServerCiphers []string `ini:"SSH_SERVER_CIPHERS"`
  260. ServerMACs []string `ini:"SSH_SERVER_MACS"`
  261. ServerAlgorithms []string `ini:"SSH_SERVER_ALGORITHMS"`
  262. }
  263. // SSH settings
  264. var SSH SSHOpts
  265. type RepositoryOpts struct {
  266. Root string
  267. ScriptType string
  268. ANSICharset string `ini:"ANSI_CHARSET"`
  269. ForcePrivate bool
  270. MaxCreationLimit int
  271. PreferredLicenses []string
  272. DisableHTTPGit bool `ini:"DISABLE_HTTP_GIT"`
  273. EnableLocalPathMigration bool
  274. EnableRawFileRenderMode bool
  275. CommitsFetchConcurrency int
  276. DefaultBranch string
  277. // Repository editor settings
  278. Editor struct {
  279. LineWrapExtensions []string
  280. PreviewableFileModes []string
  281. } `ini:"repository.editor"`
  282. // Repository upload settings
  283. Upload struct {
  284. Enabled bool
  285. TempPath string
  286. AllowedTypes []string `delim:"|"`
  287. FileMaxSize int64
  288. MaxFiles int
  289. } `ini:"repository.upload"`
  290. }
  291. // Repository settings
  292. var Repository RepositoryOpts
  293. type DatabaseOpts struct {
  294. Type string
  295. Host string
  296. Name string
  297. Schema string
  298. User string
  299. Password string
  300. SSLMode string `ini:"SSL_MODE"`
  301. Path string
  302. MaxOpenConns int
  303. MaxIdleConns int
  304. }
  305. // Database settings
  306. var Database DatabaseOpts
  307. type LFSOpts struct {
  308. Storage string
  309. ObjectsPath string
  310. ObjectsTempPath string
  311. }
  312. // LFS settings
  313. var LFS LFSOpts
  314. type UIUserOpts struct {
  315. RepoPagingNum int
  316. NewsFeedPagingNum int
  317. CommitsPagingNum int
  318. }
  319. type UIOpts struct {
  320. ExplorePagingNum int
  321. IssuePagingNum int
  322. FeedMaxCommitNum int
  323. ThemeColorMetaTag string
  324. MaxDisplayFileSize int64
  325. Admin struct {
  326. UserPagingNum int
  327. RepoPagingNum int
  328. NoticePagingNum int
  329. OrgPagingNum int
  330. } `ini:"ui.admin"`
  331. User UIUserOpts `ini:"ui.user"`
  332. }
  333. // UI settings
  334. var UI UIOpts
  335. type PictureOpts struct {
  336. AvatarUploadPath string
  337. RepositoryAvatarUploadPath string
  338. GravatarSource string
  339. DisableGravatar bool
  340. EnableFederatedAvatar bool
  341. // Derived from other static values
  342. LibravatarService *libravatar.Libravatar `ini:"-"` // Initialized client for federated avatar.
  343. }
  344. // Picture settings
  345. var Picture PictureOpts
  346. type i18nConf struct {
  347. Langs []string `delim:","`
  348. Names []string `delim:","`
  349. dateLangs map[string]string `ini:"-"`
  350. }
  351. // DateLang transforms standard language locale name to corresponding value in datetime plugin.
  352. func (c *i18nConf) DateLang(lang string) string {
  353. name, ok := c.dateLangs[lang]
  354. if ok {
  355. return name
  356. }
  357. return "en"
  358. }
  359. // I18n settings
  360. var I18n *i18nConf
  361. // handleDeprecated transfers deprecated values to the new ones when set.
  362. func handleDeprecated() {
  363. // Add fallback logic here, example:
  364. // if App.AppName != "" {
  365. // App.BrandName = App.AppName
  366. // App.AppName = ""
  367. // }
  368. }
  369. // checkInvalidOptions checks invalid (renamed/deleted) configuration sections
  370. // and options and returns a list of warnings.
  371. func checkInvalidOptions(config *ini.File) (warnings []string) {
  372. renamedSections := map[string]string{
  373. "mailer": "email",
  374. "service": "auth",
  375. }
  376. for oldSection, newSection := range renamedSections {
  377. if len(config.Section(oldSection).KeyStrings()) > 0 {
  378. warnings = append(warnings, fmt.Sprintf("section [%s] is invalid, use [%s] instead", oldSection, newSection))
  379. }
  380. }
  381. type optionPath struct {
  382. section string
  383. option string
  384. }
  385. renamedOptionPaths := map[optionPath]optionPath{
  386. // Example:
  387. // {"security", "REVERSE_PROXY_AUTHENTICATION_USER"}: {"auth", "REVERSE_PROXY_AUTHENTICATION_HEADER"},
  388. }
  389. for oldPath, newPath := range renamedOptionPaths {
  390. if config.Section(oldPath.section).HasKey(oldPath.option) {
  391. warnings = append(
  392. warnings,
  393. fmt.Sprintf("option [%s] %s is invalid, use [%s] %s instead",
  394. oldPath.section, oldPath.option,
  395. newPath.section, newPath.option,
  396. ),
  397. )
  398. }
  399. }
  400. // Check options that don't exist anymore.
  401. defaultConfigData, err := conf.Files.ReadFile("app.ini")
  402. if err != nil {
  403. // Warning is best-effort, OK to skip on error.
  404. return warnings
  405. }
  406. defaultConfig, err := ini.LoadSources(
  407. ini.LoadOptions{IgnoreInlineComment: true},
  408. defaultConfigData,
  409. )
  410. if err != nil {
  411. // Warning is best-effort, OK to skip on error.
  412. return warnings
  413. }
  414. for _, section := range config.Sections() {
  415. // Skip sections already warned about.
  416. if _, ok := renamedSections[section.Name()]; ok {
  417. continue
  418. }
  419. for _, option := range section.Keys() {
  420. if _, ok := renamedOptionPaths[optionPath{section.Name(), option.Name()}]; ok {
  421. continue
  422. }
  423. if !defaultConfig.Section(section.Name()).HasKey(option.Name()) {
  424. warnings = append(warnings, fmt.Sprintf("option [%s] %s is invalid", section.Name(), option.Name()))
  425. }
  426. }
  427. }
  428. return warnings
  429. }
  430. // HookMode indicates whether program starts as Git server-side hook callback.
  431. // All operations should be done synchronously to prevent program exits before finishing.
  432. //
  433. // ⚠️ WARNING: Should only be set by "cmd/gogs/serv.go".
  434. var HookMode bool
  435. // Indicates which database backend is currently being used.
  436. var (
  437. UseSQLite3 bool
  438. UseMySQL bool
  439. UsePostgreSQL bool
  440. )
  441. // UsersAvatarPathPrefix is the path prefix to user avatars.
  442. const UsersAvatarPathPrefix = "avatars"
  443. // UserDefaultAvatarURLPath returns the URL path of the default user avatar.
  444. func UserDefaultAvatarURLPath() string {
  445. return Server.Subpath + "/img/avatar_default.png"
  446. }