static.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  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. DisableHELO bool `ini:"DISABLE_HELO"`
  50. HELOHostname string `ini:"HELO_HOSTNAME"`
  51. SkipVerify bool
  52. UseCertificate bool
  53. CertFile string
  54. KeyFile string
  55. UsePlainText bool
  56. AddPlainTextAlt bool
  57. // Derived from other static values
  58. FromEmail string `ini:"-"` // Parsed email address of From without person's name.
  59. }
  60. // User settings
  61. User struct {
  62. EnableEmailNotification bool
  63. }
  64. // Session settings
  65. Session struct {
  66. Provider string
  67. ProviderConfig string
  68. CookieName string
  69. CookieSecure bool
  70. GCInterval int64 `ini:"GC_INTERVAL"`
  71. MaxLifeTime int64
  72. CSRFCookieName string `ini:"CSRF_COOKIE_NAME"`
  73. }
  74. // Cache settings
  75. Cache struct {
  76. Adapter string
  77. Interval int
  78. Host string
  79. }
  80. // HTTP settings
  81. HTTP struct {
  82. AccessControlAllowOrigin string
  83. }
  84. // Attachment settings
  85. Attachment struct {
  86. Enabled bool
  87. Path string
  88. AllowedTypes []string `delim:"|"`
  89. MaxSize int64
  90. MaxFiles int
  91. }
  92. // Release settings
  93. Release struct {
  94. Attachment struct {
  95. Enabled bool
  96. AllowedTypes []string `delim:"|"`
  97. MaxSize int64
  98. MaxFiles int
  99. } `ini:"release.attachment"`
  100. }
  101. // Time settings
  102. Time struct {
  103. Format string
  104. // Derived from other static values
  105. FormatLayout string `ini:"-"` // Actual layout of the Format.
  106. }
  107. // Mirror settings
  108. Mirror struct {
  109. DefaultInterval int
  110. }
  111. // Webhook settings
  112. Webhook struct {
  113. Types []string
  114. DeliverTimeout int
  115. SkipTLSVerify bool `ini:"SKIP_TLS_VERIFY"`
  116. PagingNum int
  117. }
  118. // Markdown settings
  119. Markdown struct {
  120. EnableHardLineBreak bool
  121. CustomURLSchemes []string `ini:"CUSTOM_URL_SCHEMES"`
  122. FileExtensions []string
  123. }
  124. // Smartypants settings
  125. Smartypants struct {
  126. Enabled bool
  127. Fractions bool
  128. Dashes bool
  129. LatexDashes bool
  130. AngledQuotes bool
  131. }
  132. // Admin settings
  133. Admin struct {
  134. DisableRegularOrgCreation bool
  135. }
  136. // Cron tasks
  137. Cron struct {
  138. UpdateMirror struct {
  139. Enabled bool
  140. RunAtStart bool
  141. Schedule string
  142. } `ini:"cron.update_mirrors"`
  143. RepoHealthCheck struct {
  144. Enabled bool
  145. RunAtStart bool
  146. Schedule string
  147. Timeout time.Duration
  148. Args []string `delim:" "`
  149. } `ini:"cron.repo_health_check"`
  150. CheckRepoStats struct {
  151. Enabled bool
  152. RunAtStart bool
  153. Schedule string
  154. } `ini:"cron.check_repo_stats"`
  155. RepoArchiveCleanup struct {
  156. Enabled bool
  157. RunAtStart bool
  158. Schedule string
  159. OlderThan time.Duration
  160. } `ini:"cron.repo_archive_cleanup"`
  161. }
  162. // Git settings
  163. Git struct {
  164. // ⚠️ WARNING: Should only be set by "internal/db/repo.go".
  165. Version string `ini:"-"`
  166. DisableDiffHighlight bool
  167. MaxDiffFiles int `ini:"MAX_GIT_DIFF_FILES"`
  168. MaxDiffLines int `ini:"MAX_GIT_DIFF_LINES"`
  169. MaxDiffLineChars int `ini:"MAX_GIT_DIFF_LINE_CHARACTERS"`
  170. GCArgs []string `ini:"GC_ARGS" delim:" "`
  171. Timeout struct {
  172. Migrate int
  173. Mirror int
  174. Clone int
  175. Pull int
  176. Diff int
  177. GC int `ini:"GC"`
  178. } `ini:"git.timeout"`
  179. }
  180. // API settings
  181. API struct {
  182. MaxResponseItems int
  183. }
  184. // Prometheus settings
  185. Prometheus struct {
  186. Enabled bool
  187. EnableBasicAuth bool
  188. BasicAuthUsername string
  189. BasicAuthPassword string
  190. }
  191. // Other settings
  192. Other struct {
  193. ShowFooterBranding bool
  194. ShowFooterTemplateLoadTime bool
  195. }
  196. // Global setting
  197. HasRobotsTxt bool
  198. )
  199. type AppOpts struct {
  200. // ⚠️ WARNING: Should only be set by the main package (i.e. "cmd/gogs/main.go").
  201. Version string `ini:"-"`
  202. BrandName string
  203. RunUser string
  204. RunMode string
  205. }
  206. // Application settings
  207. var App AppOpts
  208. type AuthOpts struct {
  209. ActivateCodeLives int
  210. ResetPasswordCodeLives int
  211. RequireEmailConfirmation bool
  212. RequireSigninView bool
  213. DisableRegistration bool
  214. EnableRegistrationCaptcha bool
  215. EnableReverseProxyAuthentication bool
  216. EnableReverseProxyAutoRegistration bool
  217. ReverseProxyAuthenticationHeader string
  218. CustomLogoutURL string `ini:"CUSTOM_LOGOUT_URL"`
  219. }
  220. // Authentication settings
  221. var Auth AuthOpts
  222. type ServerOpts struct {
  223. ExternalURL string `ini:"EXTERNAL_URL"`
  224. Domain string
  225. Protocol string
  226. HTTPAddr string `ini:"HTTP_ADDR"`
  227. HTTPPort string `ini:"HTTP_PORT"`
  228. CertFile string
  229. KeyFile string
  230. TLSMinVersion string `ini:"TLS_MIN_VERSION"`
  231. UnixSocketPermission string
  232. LocalRootURL string `ini:"LOCAL_ROOT_URL"`
  233. OfflineMode bool
  234. DisableRouterLog bool
  235. EnableGzip bool
  236. AppDataPath string
  237. LoadAssetsFromDisk bool
  238. LandingURL string `ini:"LANDING_URL"`
  239. // Derived from other static values
  240. URL *url.URL `ini:"-"` // Parsed URL object of ExternalURL.
  241. Subpath string `ini:"-"` // Subpath found the ExternalURL. Should be empty when not found.
  242. SubpathDepth int `ini:"-"` // The number of slashes found in the Subpath.
  243. UnixSocketMode os.FileMode `ini:"-"` // Parsed file mode of UnixSocketPermission.
  244. }
  245. // Server settings
  246. var Server ServerOpts
  247. type SSHOpts struct {
  248. Disabled bool `ini:"DISABLE_SSH"`
  249. Domain string `ini:"SSH_DOMAIN"`
  250. Port int `ini:"SSH_PORT"`
  251. RootPath string `ini:"SSH_ROOT_PATH"`
  252. KeygenPath string `ini:"SSH_KEYGEN_PATH"`
  253. KeyTestPath string `ini:"SSH_KEY_TEST_PATH"`
  254. MinimumKeySizeCheck bool
  255. MinimumKeySizes map[string]int `ini:"-"` // Load from [ssh.minimum_key_sizes]
  256. RewriteAuthorizedKeysAtStart bool
  257. StartBuiltinServer bool `ini:"START_SSH_SERVER"`
  258. ListenHost string `ini:"SSH_LISTEN_HOST"`
  259. ListenPort int `ini:"SSH_LISTEN_PORT"`
  260. ServerCiphers []string `ini:"SSH_SERVER_CIPHERS"`
  261. ServerMACs []string `ini:"SSH_SERVER_MACS"`
  262. ServerAlgorithms []string `ini:"SSH_SERVER_ALGORITHMS"`
  263. }
  264. // SSH settings
  265. var SSH SSHOpts
  266. type RepositoryOpts struct {
  267. Root string
  268. ScriptType string
  269. ANSICharset string `ini:"ANSI_CHARSET"`
  270. ForcePrivate bool
  271. MaxCreationLimit int
  272. PreferredLicenses []string
  273. DisableHTTPGit bool `ini:"DISABLE_HTTP_GIT"`
  274. EnableLocalPathMigration bool
  275. EnableRawFileRenderMode bool
  276. CommitsFetchConcurrency int
  277. DefaultBranch string
  278. // Repository editor settings
  279. Editor struct {
  280. LineWrapExtensions []string
  281. PreviewableFileModes []string
  282. } `ini:"repository.editor"`
  283. // Repository upload settings
  284. Upload struct {
  285. Enabled bool
  286. TempPath string
  287. AllowedTypes []string `delim:"|"`
  288. FileMaxSize int64
  289. MaxFiles int
  290. } `ini:"repository.upload"`
  291. }
  292. // Repository settings
  293. var Repository RepositoryOpts
  294. type DatabaseOpts struct {
  295. Type string
  296. Host string
  297. Name string
  298. Schema string
  299. User string
  300. Password string
  301. SSLMode string `ini:"SSL_MODE"`
  302. Path string
  303. MaxOpenConns int
  304. MaxIdleConns int
  305. }
  306. // Database settings
  307. var Database DatabaseOpts
  308. type LFSOpts struct {
  309. Storage string
  310. ObjectsPath 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. UseMSSQL bool
  441. )
  442. // UsersAvatarPathPrefix is the path prefix to user avatars.
  443. const UsersAvatarPathPrefix = "avatars"
  444. // UserDefaultAvatarURLPath returns the URL path of the default user avatar.
  445. func UserDefaultAvatarURLPath() string {
  446. return Server.Subpath + "/img/avatar_default.png"
  447. }