You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

setting.go 47KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2017 The Gitea Authors. All rights reserved.
  3. // SPDX-License-Identifier: MIT
  4. package setting
  5. import (
  6. "encoding/base64"
  7. "fmt"
  8. "math"
  9. "net"
  10. "net/url"
  11. "os"
  12. "os/exec"
  13. "path"
  14. "path/filepath"
  15. "runtime"
  16. "strconv"
  17. "strings"
  18. "text/template"
  19. "time"
  20. "code.gitea.io/gitea/modules/container"
  21. "code.gitea.io/gitea/modules/generate"
  22. "code.gitea.io/gitea/modules/json"
  23. "code.gitea.io/gitea/modules/log"
  24. "code.gitea.io/gitea/modules/user"
  25. "code.gitea.io/gitea/modules/util"
  26. gossh "golang.org/x/crypto/ssh"
  27. ini "gopkg.in/ini.v1"
  28. )
  29. // Scheme describes protocol types
  30. type Scheme string
  31. // enumerates all the scheme types
  32. const (
  33. HTTP Scheme = "http"
  34. HTTPS Scheme = "https"
  35. FCGI Scheme = "fcgi"
  36. FCGIUnix Scheme = "fcgi+unix"
  37. HTTPUnix Scheme = "http+unix"
  38. )
  39. // LandingPage describes the default page
  40. type LandingPage string
  41. // enumerates all the landing page types
  42. const (
  43. LandingPageHome LandingPage = "/"
  44. LandingPageExplore LandingPage = "/explore"
  45. LandingPageOrganizations LandingPage = "/explore/organizations"
  46. LandingPageLogin LandingPage = "/user/login"
  47. )
  48. // enumerates all the types of captchas
  49. const (
  50. ImageCaptcha = "image"
  51. ReCaptcha = "recaptcha"
  52. HCaptcha = "hcaptcha"
  53. MCaptcha = "mcaptcha"
  54. )
  55. // settings
  56. var (
  57. // AppVer is the version of the current build of Gitea. It is set in main.go from main.Version.
  58. AppVer string
  59. // AppBuiltWith represents a human readable version go runtime build version and build tags. (See main.go formatBuiltWith().)
  60. AppBuiltWith string
  61. // AppStartTime store time gitea has started
  62. AppStartTime time.Time
  63. // AppName is the Application name, used in the page title.
  64. // It maps to ini:"APP_NAME"
  65. AppName string
  66. // AppURL is the Application ROOT_URL. It always has a '/' suffix
  67. // It maps to ini:"ROOT_URL"
  68. AppURL string
  69. // AppSubURL represents the sub-url mounting point for gitea. It is either "" or starts with '/' and ends without '/', such as '/{subpath}'.
  70. // This value is empty if site does not have sub-url.
  71. AppSubURL string
  72. // AppPath represents the path to the gitea binary
  73. AppPath string
  74. // AppWorkPath is the "working directory" of Gitea. It maps to the environment variable GITEA_WORK_DIR.
  75. // If that is not set it is the default set here by the linker or failing that the directory of AppPath.
  76. //
  77. // AppWorkPath is used as the base path for several other paths.
  78. AppWorkPath string
  79. // AppDataPath is the default path for storing data.
  80. // It maps to ini:"APP_DATA_PATH" in [server] and defaults to AppWorkPath + "/data"
  81. AppDataPath string
  82. // LocalURL is the url for locally running applications to contact Gitea. It always has a '/' suffix
  83. // It maps to ini:"LOCAL_ROOT_URL" in [server]
  84. LocalURL string
  85. // AssetVersion holds a opaque value that is used for cache-busting assets
  86. AssetVersion string
  87. // Server settings
  88. Protocol Scheme
  89. UseProxyProtocol bool // `ini:"USE_PROXY_PROTOCOL"`
  90. ProxyProtocolTLSBridging bool //`ini:"PROXY_PROTOCOL_TLS_BRIDGING"`
  91. ProxyProtocolHeaderTimeout time.Duration
  92. ProxyProtocolAcceptUnknown bool
  93. Domain string
  94. HTTPAddr string
  95. HTTPPort string
  96. LocalUseProxyProtocol bool
  97. RedirectOtherPort bool
  98. RedirectorUseProxyProtocol bool
  99. PortToRedirect string
  100. OfflineMode bool
  101. CertFile string
  102. KeyFile string
  103. StaticRootPath string
  104. StaticCacheTime time.Duration
  105. EnableGzip bool
  106. LandingPageURL LandingPage
  107. LandingPageCustom string
  108. UnixSocketPermission uint32
  109. EnablePprof bool
  110. PprofDataPath string
  111. EnableAcme bool
  112. AcmeTOS bool
  113. AcmeLiveDirectory string
  114. AcmeEmail string
  115. AcmeURL string
  116. AcmeCARoot string
  117. SSLMinimumVersion string
  118. SSLMaximumVersion string
  119. SSLCurvePreferences []string
  120. SSLCipherSuites []string
  121. GracefulRestartable bool
  122. GracefulHammerTime time.Duration
  123. StartupTimeout time.Duration
  124. PerWriteTimeout = 30 * time.Second
  125. PerWritePerKbTimeout = 10 * time.Second
  126. StaticURLPrefix string
  127. AbsoluteAssetURL string
  128. SSH = struct {
  129. Disabled bool `ini:"DISABLE_SSH"`
  130. StartBuiltinServer bool `ini:"START_SSH_SERVER"`
  131. BuiltinServerUser string `ini:"BUILTIN_SSH_SERVER_USER"`
  132. UseProxyProtocol bool `ini:"SSH_SERVER_USE_PROXY_PROTOCOL"`
  133. Domain string `ini:"SSH_DOMAIN"`
  134. Port int `ini:"SSH_PORT"`
  135. User string `ini:"SSH_USER"`
  136. ListenHost string `ini:"SSH_LISTEN_HOST"`
  137. ListenPort int `ini:"SSH_LISTEN_PORT"`
  138. RootPath string `ini:"SSH_ROOT_PATH"`
  139. ServerCiphers []string `ini:"SSH_SERVER_CIPHERS"`
  140. ServerKeyExchanges []string `ini:"SSH_SERVER_KEY_EXCHANGES"`
  141. ServerMACs []string `ini:"SSH_SERVER_MACS"`
  142. ServerHostKeys []string `ini:"SSH_SERVER_HOST_KEYS"`
  143. KeyTestPath string `ini:"SSH_KEY_TEST_PATH"`
  144. KeygenPath string `ini:"SSH_KEYGEN_PATH"`
  145. AuthorizedKeysBackup bool `ini:"SSH_AUTHORIZED_KEYS_BACKUP"`
  146. AuthorizedPrincipalsBackup bool `ini:"SSH_AUTHORIZED_PRINCIPALS_BACKUP"`
  147. AuthorizedKeysCommandTemplate string `ini:"SSH_AUTHORIZED_KEYS_COMMAND_TEMPLATE"`
  148. AuthorizedKeysCommandTemplateTemplate *template.Template `ini:"-"`
  149. MinimumKeySizeCheck bool `ini:"-"`
  150. MinimumKeySizes map[string]int `ini:"-"`
  151. CreateAuthorizedKeysFile bool `ini:"SSH_CREATE_AUTHORIZED_KEYS_FILE"`
  152. CreateAuthorizedPrincipalsFile bool `ini:"SSH_CREATE_AUTHORIZED_PRINCIPALS_FILE"`
  153. ExposeAnonymous bool `ini:"SSH_EXPOSE_ANONYMOUS"`
  154. AuthorizedPrincipalsAllow []string `ini:"SSH_AUTHORIZED_PRINCIPALS_ALLOW"`
  155. AuthorizedPrincipalsEnabled bool `ini:"-"`
  156. TrustedUserCAKeys []string `ini:"SSH_TRUSTED_USER_CA_KEYS"`
  157. TrustedUserCAKeysFile string `ini:"SSH_TRUSTED_USER_CA_KEYS_FILENAME"`
  158. TrustedUserCAKeysParsed []gossh.PublicKey `ini:"-"`
  159. PerWriteTimeout time.Duration `ini:"SSH_PER_WRITE_TIMEOUT"`
  160. PerWritePerKbTimeout time.Duration `ini:"SSH_PER_WRITE_PER_KB_TIMEOUT"`
  161. }{
  162. Disabled: false,
  163. StartBuiltinServer: false,
  164. Domain: "",
  165. Port: 22,
  166. ServerCiphers: []string{"chacha20-poly1305@openssh.com", "aes128-ctr", "aes192-ctr", "aes256-ctr", "aes128-gcm@openssh.com", "aes256-gcm@openssh.com"},
  167. ServerKeyExchanges: []string{"curve25519-sha256", "ecdh-sha2-nistp256", "ecdh-sha2-nistp384", "ecdh-sha2-nistp521", "diffie-hellman-group14-sha256", "diffie-hellman-group14-sha1"},
  168. ServerMACs: []string{"hmac-sha2-256-etm@openssh.com", "hmac-sha2-256", "hmac-sha1"},
  169. KeygenPath: "ssh-keygen",
  170. MinimumKeySizeCheck: true,
  171. MinimumKeySizes: map[string]int{"ed25519": 256, "ed25519-sk": 256, "ecdsa": 256, "ecdsa-sk": 256, "rsa": 2047},
  172. ServerHostKeys: []string{"ssh/gitea.rsa", "ssh/gogs.rsa"},
  173. AuthorizedKeysCommandTemplate: "{{.AppPath}} --config={{.CustomConf}} serv key-{{.Key.ID}}",
  174. PerWriteTimeout: PerWriteTimeout,
  175. PerWritePerKbTimeout: PerWritePerKbTimeout,
  176. }
  177. // Security settings
  178. InstallLock bool
  179. SecretKey string
  180. LogInRememberDays int
  181. CookieUserName string
  182. CookieRememberName string
  183. ReverseProxyAuthUser string
  184. ReverseProxyAuthEmail string
  185. ReverseProxyAuthFullName string
  186. ReverseProxyLimit int
  187. ReverseProxyTrustedProxies []string
  188. MinPasswordLength int
  189. ImportLocalPaths bool
  190. DisableGitHooks bool
  191. DisableWebhooks bool
  192. OnlyAllowPushIfGiteaEnvironmentSet bool
  193. PasswordComplexity []string
  194. PasswordHashAlgo string
  195. PasswordCheckPwn bool
  196. SuccessfulTokensCacheSize int
  197. Camo = struct {
  198. Enabled bool
  199. ServerURL string `ini:"SERVER_URL"`
  200. HMACKey string `ini:"HMAC_KEY"`
  201. Allways bool
  202. }{}
  203. // UI settings
  204. UI = struct {
  205. ExplorePagingNum int
  206. SitemapPagingNum int
  207. IssuePagingNum int
  208. RepoSearchPagingNum int
  209. MembersPagingNum int
  210. FeedMaxCommitNum int
  211. FeedPagingNum int
  212. PackagesPagingNum int
  213. GraphMaxCommitNum int
  214. CodeCommentLines int
  215. ReactionMaxUserNum int
  216. ThemeColorMetaTag string
  217. MaxDisplayFileSize int64
  218. ShowUserEmail bool
  219. DefaultShowFullName bool
  220. DefaultTheme string
  221. Themes []string
  222. Reactions []string
  223. ReactionsLookup container.Set[string] `ini:"-"`
  224. CustomEmojis []string
  225. CustomEmojisMap map[string]string `ini:"-"`
  226. SearchRepoDescription bool
  227. UseServiceWorker bool
  228. OnlyShowRelevantRepos bool
  229. Notification struct {
  230. MinTimeout time.Duration
  231. TimeoutStep time.Duration
  232. MaxTimeout time.Duration
  233. EventSourceUpdateTime time.Duration
  234. } `ini:"ui.notification"`
  235. SVG struct {
  236. Enabled bool `ini:"ENABLE_RENDER"`
  237. } `ini:"ui.svg"`
  238. CSV struct {
  239. MaxFileSize int64
  240. } `ini:"ui.csv"`
  241. Admin struct {
  242. UserPagingNum int
  243. RepoPagingNum int
  244. NoticePagingNum int
  245. OrgPagingNum int
  246. } `ini:"ui.admin"`
  247. User struct {
  248. RepoPagingNum int
  249. } `ini:"ui.user"`
  250. Meta struct {
  251. Author string
  252. Description string
  253. Keywords string
  254. } `ini:"ui.meta"`
  255. }{
  256. ExplorePagingNum: 20,
  257. SitemapPagingNum: 20,
  258. IssuePagingNum: 20,
  259. RepoSearchPagingNum: 20,
  260. MembersPagingNum: 20,
  261. FeedMaxCommitNum: 5,
  262. FeedPagingNum: 20,
  263. PackagesPagingNum: 20,
  264. GraphMaxCommitNum: 100,
  265. CodeCommentLines: 4,
  266. ReactionMaxUserNum: 10,
  267. ThemeColorMetaTag: `#6cc644`,
  268. MaxDisplayFileSize: 8388608,
  269. DefaultTheme: `auto`,
  270. Themes: []string{`auto`, `gitea`, `arc-green`},
  271. Reactions: []string{`+1`, `-1`, `laugh`, `hooray`, `confused`, `heart`, `rocket`, `eyes`},
  272. CustomEmojis: []string{`git`, `gitea`, `codeberg`, `gitlab`, `github`, `gogs`},
  273. CustomEmojisMap: map[string]string{"git": ":git:", "gitea": ":gitea:", "codeberg": ":codeberg:", "gitlab": ":gitlab:", "github": ":github:", "gogs": ":gogs:"},
  274. Notification: struct {
  275. MinTimeout time.Duration
  276. TimeoutStep time.Duration
  277. MaxTimeout time.Duration
  278. EventSourceUpdateTime time.Duration
  279. }{
  280. MinTimeout: 10 * time.Second,
  281. TimeoutStep: 10 * time.Second,
  282. MaxTimeout: 60 * time.Second,
  283. EventSourceUpdateTime: 10 * time.Second,
  284. },
  285. SVG: struct {
  286. Enabled bool `ini:"ENABLE_RENDER"`
  287. }{
  288. Enabled: true,
  289. },
  290. CSV: struct {
  291. MaxFileSize int64
  292. }{
  293. MaxFileSize: 524288,
  294. },
  295. Admin: struct {
  296. UserPagingNum int
  297. RepoPagingNum int
  298. NoticePagingNum int
  299. OrgPagingNum int
  300. }{
  301. UserPagingNum: 50,
  302. RepoPagingNum: 50,
  303. NoticePagingNum: 25,
  304. OrgPagingNum: 50,
  305. },
  306. User: struct {
  307. RepoPagingNum int
  308. }{
  309. RepoPagingNum: 15,
  310. },
  311. Meta: struct {
  312. Author string
  313. Description string
  314. Keywords string
  315. }{
  316. Author: "Gitea - Git with a cup of tea",
  317. Description: "Gitea (Git with a cup of tea) is a painless self-hosted Git service written in Go",
  318. Keywords: "go,git,self-hosted,gitea",
  319. },
  320. }
  321. // Markdown settings
  322. Markdown = struct {
  323. EnableHardLineBreakInComments bool
  324. EnableHardLineBreakInDocuments bool
  325. CustomURLSchemes []string `ini:"CUSTOM_URL_SCHEMES"`
  326. FileExtensions []string
  327. EnableMath bool
  328. }{
  329. EnableHardLineBreakInComments: true,
  330. EnableHardLineBreakInDocuments: false,
  331. FileExtensions: strings.Split(".md,.markdown,.mdown,.mkd", ","),
  332. EnableMath: true,
  333. }
  334. // Admin settings
  335. Admin struct {
  336. DisableRegularOrgCreation bool
  337. DefaultEmailNotification string
  338. }
  339. // Log settings
  340. LogLevel log.Level
  341. StacktraceLogLevel string
  342. LogRootPath string
  343. EnableSSHLog bool
  344. EnableXORMLog bool
  345. DisableRouterLog bool
  346. EnableAccessLog bool
  347. AccessLogTemplate string
  348. // Time settings
  349. TimeFormat string
  350. // UILocation is the location on the UI, so that we can display the time on UI.
  351. DefaultUILocation = time.Local
  352. CSRFCookieName = "_csrf"
  353. CSRFCookieHTTPOnly = true
  354. ManifestData string
  355. // API settings
  356. API = struct {
  357. EnableSwagger bool
  358. SwaggerURL string
  359. MaxResponseItems int
  360. DefaultPagingNum int
  361. DefaultGitTreesPerPage int
  362. DefaultMaxBlobSize int64
  363. }{
  364. EnableSwagger: true,
  365. SwaggerURL: "",
  366. MaxResponseItems: 50,
  367. DefaultPagingNum: 30,
  368. DefaultGitTreesPerPage: 1000,
  369. DefaultMaxBlobSize: 10485760,
  370. }
  371. OAuth2 = struct {
  372. Enable bool
  373. AccessTokenExpirationTime int64
  374. RefreshTokenExpirationTime int64
  375. InvalidateRefreshTokens bool
  376. JWTSigningAlgorithm string `ini:"JWT_SIGNING_ALGORITHM"`
  377. JWTSecretBase64 string `ini:"JWT_SECRET"`
  378. JWTSigningPrivateKeyFile string `ini:"JWT_SIGNING_PRIVATE_KEY_FILE"`
  379. MaxTokenLength int
  380. }{
  381. Enable: true,
  382. AccessTokenExpirationTime: 3600,
  383. RefreshTokenExpirationTime: 730,
  384. InvalidateRefreshTokens: false,
  385. JWTSigningAlgorithm: "RS256",
  386. JWTSigningPrivateKeyFile: "jwt/private.pem",
  387. MaxTokenLength: math.MaxInt16,
  388. }
  389. // Metrics settings
  390. Metrics = struct {
  391. Enabled bool
  392. Token string
  393. EnabledIssueByLabel bool
  394. EnabledIssueByRepository bool
  395. }{
  396. Enabled: false,
  397. Token: "",
  398. EnabledIssueByLabel: false,
  399. EnabledIssueByRepository: false,
  400. }
  401. // I18n settings
  402. Langs []string
  403. Names []string
  404. // Highlight settings are loaded in modules/template/highlight.go
  405. // Other settings
  406. ShowFooterBranding bool
  407. ShowFooterVersion bool
  408. ShowFooterTemplateLoadTime bool
  409. EnableFeed bool
  410. // Global setting objects
  411. Cfg *ini.File
  412. CustomPath string // Custom directory path
  413. CustomConf string
  414. PIDFile = "/run/gitea.pid"
  415. WritePIDFile bool
  416. RunMode string
  417. IsProd bool
  418. RunUser string
  419. IsWindows bool
  420. HasRobotsTxt bool
  421. EnableSitemap bool
  422. InternalToken string // internal access token
  423. )
  424. func getAppPath() (string, error) {
  425. var appPath string
  426. var err error
  427. if IsWindows && filepath.IsAbs(os.Args[0]) {
  428. appPath = filepath.Clean(os.Args[0])
  429. } else {
  430. appPath, err = exec.LookPath(os.Args[0])
  431. }
  432. if err != nil {
  433. // FIXME: Once we switch to go 1.19 use !errors.Is(err, exec.ErrDot)
  434. if !strings.Contains(err.Error(), "cannot run executable found relative to current directory") {
  435. return "", err
  436. }
  437. appPath, err = filepath.Abs(os.Args[0])
  438. }
  439. if err != nil {
  440. return "", err
  441. }
  442. appPath, err = filepath.Abs(appPath)
  443. if err != nil {
  444. return "", err
  445. }
  446. // Note: we don't use path.Dir here because it does not handle case
  447. // which path starts with two "/" in Windows: "//psf/Home/..."
  448. return strings.ReplaceAll(appPath, "\\", "/"), err
  449. }
  450. func getWorkPath(appPath string) string {
  451. workPath := AppWorkPath
  452. if giteaWorkPath, ok := os.LookupEnv("GITEA_WORK_DIR"); ok {
  453. workPath = giteaWorkPath
  454. }
  455. if len(workPath) == 0 {
  456. i := strings.LastIndex(appPath, "/")
  457. if i == -1 {
  458. workPath = appPath
  459. } else {
  460. workPath = appPath[:i]
  461. }
  462. }
  463. workPath = strings.ReplaceAll(workPath, "\\", "/")
  464. if !filepath.IsAbs(workPath) {
  465. log.Info("Provided work path %s is not absolute - will be made absolute against the current working directory", workPath)
  466. absPath, err := filepath.Abs(workPath)
  467. if err != nil {
  468. log.Error("Unable to absolute %s against the current working directory %v. Will absolute against the AppPath %s", workPath, err, appPath)
  469. workPath = filepath.Join(appPath, workPath)
  470. } else {
  471. workPath = absPath
  472. }
  473. }
  474. return strings.ReplaceAll(workPath, "\\", "/")
  475. }
  476. func init() {
  477. IsWindows = runtime.GOOS == "windows"
  478. // We can rely on log.CanColorStdout being set properly because modules/log/console_windows.go comes before modules/setting/setting.go lexicographically
  479. // By default set this logger at Info - we'll change it later but we need to start with something.
  480. log.NewLogger(0, "console", "console", fmt.Sprintf(`{"level": "info", "colorize": %t, "stacktraceLevel": "none"}`, log.CanColorStdout))
  481. var err error
  482. if AppPath, err = getAppPath(); err != nil {
  483. log.Fatal("Failed to get app path: %v", err)
  484. }
  485. AppWorkPath = getWorkPath(AppPath)
  486. }
  487. func forcePathSeparator(path string) {
  488. if strings.Contains(path, "\\") {
  489. log.Fatal("Do not use '\\' or '\\\\' in paths, instead, please use '/' in all places")
  490. }
  491. }
  492. // IsRunUserMatchCurrentUser returns false if configured run user does not match
  493. // actual user that runs the app. The first return value is the actual user name.
  494. // This check is ignored under Windows since SSH remote login is not the main
  495. // method to login on Windows.
  496. func IsRunUserMatchCurrentUser(runUser string) (string, bool) {
  497. if IsWindows || SSH.StartBuiltinServer {
  498. return "", true
  499. }
  500. currentUser := user.CurrentUsername()
  501. return currentUser, runUser == currentUser
  502. }
  503. func createPIDFile(pidPath string) {
  504. currentPid := os.Getpid()
  505. if err := os.MkdirAll(filepath.Dir(pidPath), os.ModePerm); err != nil {
  506. log.Fatal("Failed to create PID folder: %v", err)
  507. }
  508. file, err := os.Create(pidPath)
  509. if err != nil {
  510. log.Fatal("Failed to create PID file: %v", err)
  511. }
  512. defer file.Close()
  513. if _, err := file.WriteString(strconv.FormatInt(int64(currentPid), 10)); err != nil {
  514. log.Fatal("Failed to write PID information: %v", err)
  515. }
  516. }
  517. // SetCustomPathAndConf will set CustomPath and CustomConf with reference to the
  518. // GITEA_CUSTOM environment variable and with provided overrides before stepping
  519. // back to the default
  520. func SetCustomPathAndConf(providedCustom, providedConf, providedWorkPath string) {
  521. if len(providedWorkPath) != 0 {
  522. AppWorkPath = filepath.ToSlash(providedWorkPath)
  523. }
  524. if giteaCustom, ok := os.LookupEnv("GITEA_CUSTOM"); ok {
  525. CustomPath = giteaCustom
  526. }
  527. if len(providedCustom) != 0 {
  528. CustomPath = providedCustom
  529. }
  530. if len(CustomPath) == 0 {
  531. CustomPath = path.Join(AppWorkPath, "custom")
  532. } else if !filepath.IsAbs(CustomPath) {
  533. CustomPath = path.Join(AppWorkPath, CustomPath)
  534. }
  535. if len(providedConf) != 0 {
  536. CustomConf = providedConf
  537. }
  538. if len(CustomConf) == 0 {
  539. CustomConf = path.Join(CustomPath, "conf/app.ini")
  540. } else if !filepath.IsAbs(CustomConf) {
  541. CustomConf = path.Join(CustomPath, CustomConf)
  542. log.Warn("Using 'custom' directory as relative origin for configuration file: '%s'", CustomConf)
  543. }
  544. }
  545. // LoadFromExisting initializes setting options from an existing config file (app.ini)
  546. func LoadFromExisting() {
  547. loadFromConf(false, "")
  548. }
  549. // LoadAllowEmpty initializes setting options, it's also fine that if the config file (app.ini) doesn't exist
  550. func LoadAllowEmpty() {
  551. loadFromConf(true, "")
  552. }
  553. // LoadForTest initializes setting options for tests
  554. func LoadForTest(extraConfigs ...string) {
  555. loadFromConf(true, strings.Join(extraConfigs, "\n"))
  556. if err := PrepareAppDataPath(); err != nil {
  557. log.Fatal("Can not prepare APP_DATA_PATH: %v", err)
  558. }
  559. }
  560. func deprecatedSetting(oldSection, oldKey, newSection, newKey string) {
  561. if Cfg.Section(oldSection).HasKey(oldKey) {
  562. log.Error("Deprecated fallback `[%s]` `%s` present. Use `[%s]` `%s` instead. This fallback will be removed in v1.19.0", oldSection, oldKey, newSection, newKey)
  563. }
  564. }
  565. // deprecatedSettingDB add a hint that the configuration has been moved to database but still kept in app.ini
  566. func deprecatedSettingDB(oldSection, oldKey string) {
  567. if Cfg.Section(oldSection).HasKey(oldKey) {
  568. log.Error("Deprecated `[%s]` `%s` present which has been copied to database table sys_setting", oldSection, oldKey)
  569. }
  570. }
  571. // loadFromConf initializes configuration context.
  572. // NOTE: do not print any log except error.
  573. func loadFromConf(allowEmpty bool, extraConfig string) {
  574. Cfg = ini.Empty()
  575. if WritePIDFile && len(PIDFile) > 0 {
  576. createPIDFile(PIDFile)
  577. }
  578. isFile, err := util.IsFile(CustomConf)
  579. if err != nil {
  580. log.Error("Unable to check if %s is a file. Error: %v", CustomConf, err)
  581. }
  582. if isFile {
  583. if err := Cfg.Append(CustomConf); err != nil {
  584. log.Fatal("Failed to load custom conf '%s': %v", CustomConf, err)
  585. }
  586. } else if !allowEmpty {
  587. log.Fatal("Unable to find configuration file: %q.\nEnsure you are running in the correct environment or set the correct configuration file with -c.", CustomConf)
  588. } // else: no config file, a config file might be created at CustomConf later (might not)
  589. if extraConfig != "" {
  590. if err = Cfg.Append([]byte(extraConfig)); err != nil {
  591. log.Fatal("Unable to append more config: %v", err)
  592. }
  593. }
  594. Cfg.NameMapper = ini.SnackCase
  595. homeDir, err := util.HomeDir()
  596. if err != nil {
  597. log.Fatal("Failed to get home directory: %v", err)
  598. }
  599. homeDir = strings.ReplaceAll(homeDir, "\\", "/")
  600. LogLevel = getLogLevel(Cfg.Section("log"), "LEVEL", log.INFO)
  601. StacktraceLogLevel = getStacktraceLogLevel(Cfg.Section("log"), "STACKTRACE_LEVEL", "None")
  602. LogRootPath = Cfg.Section("log").Key("ROOT_PATH").MustString(path.Join(AppWorkPath, "log"))
  603. forcePathSeparator(LogRootPath)
  604. sec := Cfg.Section("server")
  605. AppName = Cfg.Section("").Key("APP_NAME").MustString("Gitea: Git with a cup of tea")
  606. Domain = sec.Key("DOMAIN").MustString("localhost")
  607. HTTPAddr = sec.Key("HTTP_ADDR").MustString("0.0.0.0")
  608. HTTPPort = sec.Key("HTTP_PORT").MustString("3000")
  609. Protocol = HTTP
  610. protocolCfg := sec.Key("PROTOCOL").String()
  611. switch protocolCfg {
  612. case "https":
  613. Protocol = HTTPS
  614. // FIXME: DEPRECATED to be removed in v1.18.0
  615. if sec.HasKey("ENABLE_ACME") {
  616. EnableAcme = sec.Key("ENABLE_ACME").MustBool(false)
  617. } else {
  618. deprecatedSetting("server", "ENABLE_LETSENCRYPT", "server", "ENABLE_ACME")
  619. EnableAcme = sec.Key("ENABLE_LETSENCRYPT").MustBool(false)
  620. }
  621. if EnableAcme {
  622. AcmeURL = sec.Key("ACME_URL").MustString("")
  623. AcmeCARoot = sec.Key("ACME_CA_ROOT").MustString("")
  624. // FIXME: DEPRECATED to be removed in v1.18.0
  625. if sec.HasKey("ACME_ACCEPTTOS") {
  626. AcmeTOS = sec.Key("ACME_ACCEPTTOS").MustBool(false)
  627. } else {
  628. deprecatedSetting("server", "LETSENCRYPT_ACCEPTTOS", "server", "ACME_ACCEPTTOS")
  629. AcmeTOS = sec.Key("LETSENCRYPT_ACCEPTTOS").MustBool(false)
  630. }
  631. if !AcmeTOS {
  632. log.Fatal("ACME TOS is not accepted (ACME_ACCEPTTOS).")
  633. }
  634. // FIXME: DEPRECATED to be removed in v1.18.0
  635. if sec.HasKey("ACME_DIRECTORY") {
  636. AcmeLiveDirectory = sec.Key("ACME_DIRECTORY").MustString("https")
  637. } else {
  638. deprecatedSetting("server", "LETSENCRYPT_DIRECTORY", "server", "ACME_DIRECTORY")
  639. AcmeLiveDirectory = sec.Key("LETSENCRYPT_DIRECTORY").MustString("https")
  640. }
  641. // FIXME: DEPRECATED to be removed in v1.18.0
  642. if sec.HasKey("ACME_EMAIL") {
  643. AcmeEmail = sec.Key("ACME_EMAIL").MustString("")
  644. } else {
  645. deprecatedSetting("server", "LETSENCRYPT_EMAIL", "server", "ACME_EMAIL")
  646. AcmeEmail = sec.Key("LETSENCRYPT_EMAIL").MustString("")
  647. }
  648. } else {
  649. CertFile = sec.Key("CERT_FILE").String()
  650. KeyFile = sec.Key("KEY_FILE").String()
  651. if len(CertFile) > 0 && !filepath.IsAbs(CertFile) {
  652. CertFile = filepath.Join(CustomPath, CertFile)
  653. }
  654. if len(KeyFile) > 0 && !filepath.IsAbs(KeyFile) {
  655. KeyFile = filepath.Join(CustomPath, KeyFile)
  656. }
  657. }
  658. SSLMinimumVersion = sec.Key("SSL_MIN_VERSION").MustString("")
  659. SSLMaximumVersion = sec.Key("SSL_MAX_VERSION").MustString("")
  660. SSLCurvePreferences = sec.Key("SSL_CURVE_PREFERENCES").Strings(",")
  661. SSLCipherSuites = sec.Key("SSL_CIPHER_SUITES").Strings(",")
  662. case "fcgi":
  663. Protocol = FCGI
  664. case "fcgi+unix", "unix", "http+unix":
  665. switch protocolCfg {
  666. case "fcgi+unix":
  667. Protocol = FCGIUnix
  668. case "unix":
  669. log.Warn("unix PROTOCOL value is deprecated, please use http+unix")
  670. fallthrough
  671. case "http+unix":
  672. Protocol = HTTPUnix
  673. }
  674. UnixSocketPermissionRaw := sec.Key("UNIX_SOCKET_PERMISSION").MustString("666")
  675. UnixSocketPermissionParsed, err := strconv.ParseUint(UnixSocketPermissionRaw, 8, 32)
  676. if err != nil || UnixSocketPermissionParsed > 0o777 {
  677. log.Fatal("Failed to parse unixSocketPermission: %s", UnixSocketPermissionRaw)
  678. }
  679. UnixSocketPermission = uint32(UnixSocketPermissionParsed)
  680. if !filepath.IsAbs(HTTPAddr) {
  681. HTTPAddr = filepath.Join(AppWorkPath, HTTPAddr)
  682. }
  683. }
  684. UseProxyProtocol = sec.Key("USE_PROXY_PROTOCOL").MustBool(false)
  685. ProxyProtocolTLSBridging = sec.Key("PROXY_PROTOCOL_TLS_BRIDGING").MustBool(false)
  686. ProxyProtocolHeaderTimeout = sec.Key("PROXY_PROTOCOL_HEADER_TIMEOUT").MustDuration(5 * time.Second)
  687. ProxyProtocolAcceptUnknown = sec.Key("PROXY_PROTOCOL_ACCEPT_UNKNOWN").MustBool(false)
  688. GracefulRestartable = sec.Key("ALLOW_GRACEFUL_RESTARTS").MustBool(true)
  689. GracefulHammerTime = sec.Key("GRACEFUL_HAMMER_TIME").MustDuration(60 * time.Second)
  690. StartupTimeout = sec.Key("STARTUP_TIMEOUT").MustDuration(0 * time.Second)
  691. PerWriteTimeout = sec.Key("PER_WRITE_TIMEOUT").MustDuration(PerWriteTimeout)
  692. PerWritePerKbTimeout = sec.Key("PER_WRITE_PER_KB_TIMEOUT").MustDuration(PerWritePerKbTimeout)
  693. defaultAppURL := string(Protocol) + "://" + Domain + ":" + HTTPPort
  694. AppURL = sec.Key("ROOT_URL").MustString(defaultAppURL)
  695. // Check validity of AppURL
  696. appURL, err := url.Parse(AppURL)
  697. if err != nil {
  698. log.Fatal("Invalid ROOT_URL '%s': %s", AppURL, err)
  699. }
  700. // Remove default ports from AppURL.
  701. // (scheme-based URL normalization, RFC 3986 section 6.2.3)
  702. if (appURL.Scheme == string(HTTP) && appURL.Port() == "80") || (appURL.Scheme == string(HTTPS) && appURL.Port() == "443") {
  703. appURL.Host = appURL.Hostname()
  704. }
  705. // This should be TrimRight to ensure that there is only a single '/' at the end of AppURL.
  706. AppURL = strings.TrimRight(appURL.String(), "/") + "/"
  707. // Suburl should start with '/' and end without '/', such as '/{subpath}'.
  708. // This value is empty if site does not have sub-url.
  709. AppSubURL = strings.TrimSuffix(appURL.Path, "/")
  710. StaticURLPrefix = strings.TrimSuffix(sec.Key("STATIC_URL_PREFIX").MustString(AppSubURL), "/")
  711. // Check if Domain differs from AppURL domain than update it to AppURL's domain
  712. urlHostname := appURL.Hostname()
  713. if urlHostname != Domain && net.ParseIP(urlHostname) == nil && urlHostname != "" {
  714. Domain = urlHostname
  715. }
  716. AbsoluteAssetURL = MakeAbsoluteAssetURL(AppURL, StaticURLPrefix)
  717. AssetVersion = strings.ReplaceAll(AppVer, "+", "~") // make sure the version string is clear (no real escaping is needed)
  718. manifestBytes := MakeManifestData(AppName, AppURL, AbsoluteAssetURL)
  719. ManifestData = `application/json;base64,` + base64.StdEncoding.EncodeToString(manifestBytes)
  720. var defaultLocalURL string
  721. switch Protocol {
  722. case HTTPUnix:
  723. defaultLocalURL = "http://unix/"
  724. case FCGI:
  725. defaultLocalURL = AppURL
  726. case FCGIUnix:
  727. defaultLocalURL = AppURL
  728. default:
  729. defaultLocalURL = string(Protocol) + "://"
  730. if HTTPAddr == "0.0.0.0" {
  731. defaultLocalURL += net.JoinHostPort("localhost", HTTPPort) + "/"
  732. } else {
  733. defaultLocalURL += net.JoinHostPort(HTTPAddr, HTTPPort) + "/"
  734. }
  735. }
  736. LocalURL = sec.Key("LOCAL_ROOT_URL").MustString(defaultLocalURL)
  737. LocalURL = strings.TrimRight(LocalURL, "/") + "/"
  738. LocalUseProxyProtocol = sec.Key("LOCAL_USE_PROXY_PROTOCOL").MustBool(UseProxyProtocol)
  739. RedirectOtherPort = sec.Key("REDIRECT_OTHER_PORT").MustBool(false)
  740. PortToRedirect = sec.Key("PORT_TO_REDIRECT").MustString("80")
  741. RedirectorUseProxyProtocol = sec.Key("REDIRECTOR_USE_PROXY_PROTOCOL").MustBool(UseProxyProtocol)
  742. OfflineMode = sec.Key("OFFLINE_MODE").MustBool()
  743. DisableRouterLog = sec.Key("DISABLE_ROUTER_LOG").MustBool()
  744. if len(StaticRootPath) == 0 {
  745. StaticRootPath = AppWorkPath
  746. }
  747. StaticRootPath = sec.Key("STATIC_ROOT_PATH").MustString(StaticRootPath)
  748. StaticCacheTime = sec.Key("STATIC_CACHE_TIME").MustDuration(6 * time.Hour)
  749. AppDataPath = sec.Key("APP_DATA_PATH").MustString(path.Join(AppWorkPath, "data"))
  750. if !filepath.IsAbs(AppDataPath) {
  751. log.Info("The provided APP_DATA_PATH: %s is not absolute - it will be made absolute against the work path: %s", AppDataPath, AppWorkPath)
  752. AppDataPath = filepath.ToSlash(filepath.Join(AppWorkPath, AppDataPath))
  753. }
  754. EnableGzip = sec.Key("ENABLE_GZIP").MustBool()
  755. EnablePprof = sec.Key("ENABLE_PPROF").MustBool(false)
  756. PprofDataPath = sec.Key("PPROF_DATA_PATH").MustString(path.Join(AppWorkPath, "data/tmp/pprof"))
  757. if !filepath.IsAbs(PprofDataPath) {
  758. PprofDataPath = filepath.Join(AppWorkPath, PprofDataPath)
  759. }
  760. landingPage := sec.Key("LANDING_PAGE").MustString("home")
  761. switch landingPage {
  762. case "explore":
  763. LandingPageURL = LandingPageExplore
  764. case "organizations":
  765. LandingPageURL = LandingPageOrganizations
  766. case "login":
  767. LandingPageURL = LandingPageLogin
  768. case "":
  769. case "home":
  770. LandingPageURL = LandingPageHome
  771. default:
  772. LandingPageURL = LandingPage(landingPage)
  773. }
  774. if len(SSH.Domain) == 0 {
  775. SSH.Domain = Domain
  776. }
  777. SSH.RootPath = path.Join(homeDir, ".ssh")
  778. serverCiphers := sec.Key("SSH_SERVER_CIPHERS").Strings(",")
  779. if len(serverCiphers) > 0 {
  780. SSH.ServerCiphers = serverCiphers
  781. }
  782. serverKeyExchanges := sec.Key("SSH_SERVER_KEY_EXCHANGES").Strings(",")
  783. if len(serverKeyExchanges) > 0 {
  784. SSH.ServerKeyExchanges = serverKeyExchanges
  785. }
  786. serverMACs := sec.Key("SSH_SERVER_MACS").Strings(",")
  787. if len(serverMACs) > 0 {
  788. SSH.ServerMACs = serverMACs
  789. }
  790. SSH.KeyTestPath = os.TempDir()
  791. if err = Cfg.Section("server").MapTo(&SSH); err != nil {
  792. log.Fatal("Failed to map SSH settings: %v", err)
  793. }
  794. for i, key := range SSH.ServerHostKeys {
  795. if !filepath.IsAbs(key) {
  796. SSH.ServerHostKeys[i] = filepath.Join(AppDataPath, key)
  797. }
  798. }
  799. SSH.KeygenPath = sec.Key("SSH_KEYGEN_PATH").MustString("ssh-keygen")
  800. SSH.Port = sec.Key("SSH_PORT").MustInt(22)
  801. SSH.ListenPort = sec.Key("SSH_LISTEN_PORT").MustInt(SSH.Port)
  802. SSH.UseProxyProtocol = sec.Key("SSH_SERVER_USE_PROXY_PROTOCOL").MustBool(false)
  803. // When disable SSH, start builtin server value is ignored.
  804. if SSH.Disabled {
  805. SSH.StartBuiltinServer = false
  806. }
  807. SSH.TrustedUserCAKeysFile = sec.Key("SSH_TRUSTED_USER_CA_KEYS_FILENAME").MustString(filepath.Join(SSH.RootPath, "gitea-trusted-user-ca-keys.pem"))
  808. for _, caKey := range SSH.TrustedUserCAKeys {
  809. pubKey, _, _, _, err := gossh.ParseAuthorizedKey([]byte(caKey))
  810. if err != nil {
  811. log.Fatal("Failed to parse TrustedUserCaKeys: %s %v", caKey, err)
  812. }
  813. SSH.TrustedUserCAKeysParsed = append(SSH.TrustedUserCAKeysParsed, pubKey)
  814. }
  815. if len(SSH.TrustedUserCAKeys) > 0 {
  816. // Set the default as email,username otherwise we can leave it empty
  817. sec.Key("SSH_AUTHORIZED_PRINCIPALS_ALLOW").MustString("username,email")
  818. } else {
  819. sec.Key("SSH_AUTHORIZED_PRINCIPALS_ALLOW").MustString("off")
  820. }
  821. SSH.AuthorizedPrincipalsAllow, SSH.AuthorizedPrincipalsEnabled = parseAuthorizedPrincipalsAllow(sec.Key("SSH_AUTHORIZED_PRINCIPALS_ALLOW").Strings(","))
  822. SSH.MinimumKeySizeCheck = sec.Key("MINIMUM_KEY_SIZE_CHECK").MustBool(SSH.MinimumKeySizeCheck)
  823. minimumKeySizes := Cfg.Section("ssh.minimum_key_sizes").Keys()
  824. for _, key := range minimumKeySizes {
  825. if key.MustInt() != -1 {
  826. SSH.MinimumKeySizes[strings.ToLower(key.Name())] = key.MustInt()
  827. } else {
  828. delete(SSH.MinimumKeySizes, strings.ToLower(key.Name()))
  829. }
  830. }
  831. SSH.AuthorizedKeysBackup = sec.Key("SSH_AUTHORIZED_KEYS_BACKUP").MustBool(true)
  832. SSH.CreateAuthorizedKeysFile = sec.Key("SSH_CREATE_AUTHORIZED_KEYS_FILE").MustBool(true)
  833. SSH.AuthorizedPrincipalsBackup = false
  834. SSH.CreateAuthorizedPrincipalsFile = false
  835. if SSH.AuthorizedPrincipalsEnabled {
  836. SSH.AuthorizedPrincipalsBackup = sec.Key("SSH_AUTHORIZED_PRINCIPALS_BACKUP").MustBool(true)
  837. SSH.CreateAuthorizedPrincipalsFile = sec.Key("SSH_CREATE_AUTHORIZED_PRINCIPALS_FILE").MustBool(true)
  838. }
  839. SSH.ExposeAnonymous = sec.Key("SSH_EXPOSE_ANONYMOUS").MustBool(false)
  840. SSH.AuthorizedKeysCommandTemplate = sec.Key("SSH_AUTHORIZED_KEYS_COMMAND_TEMPLATE").MustString(SSH.AuthorizedKeysCommandTemplate)
  841. SSH.AuthorizedKeysCommandTemplateTemplate = template.Must(template.New("").Parse(SSH.AuthorizedKeysCommandTemplate))
  842. SSH.PerWriteTimeout = sec.Key("SSH_PER_WRITE_TIMEOUT").MustDuration(PerWriteTimeout)
  843. SSH.PerWritePerKbTimeout = sec.Key("SSH_PER_WRITE_PER_KB_TIMEOUT").MustDuration(PerWritePerKbTimeout)
  844. if err = Cfg.Section("oauth2").MapTo(&OAuth2); err != nil {
  845. log.Fatal("Failed to OAuth2 settings: %v", err)
  846. return
  847. }
  848. if !filepath.IsAbs(OAuth2.JWTSigningPrivateKeyFile) {
  849. OAuth2.JWTSigningPrivateKeyFile = filepath.Join(AppDataPath, OAuth2.JWTSigningPrivateKeyFile)
  850. }
  851. sec = Cfg.Section("admin")
  852. Admin.DefaultEmailNotification = sec.Key("DEFAULT_EMAIL_NOTIFICATIONS").MustString("enabled")
  853. sec = Cfg.Section("security")
  854. InstallLock = sec.Key("INSTALL_LOCK").MustBool(false)
  855. LogInRememberDays = sec.Key("LOGIN_REMEMBER_DAYS").MustInt(7)
  856. CookieUserName = sec.Key("COOKIE_USERNAME").MustString("gitea_awesome")
  857. SecretKey = loadSecret(sec, "SECRET_KEY_URI", "SECRET_KEY")
  858. if SecretKey == "" {
  859. // FIXME: https://github.com/go-gitea/gitea/issues/16832
  860. // Until it supports rotating an existing secret key, we shouldn't move users off of the widely used default value
  861. SecretKey = "!#@FDEWREWR&*(" //nolint:gosec
  862. }
  863. CookieRememberName = sec.Key("COOKIE_REMEMBER_NAME").MustString("gitea_incredible")
  864. ReverseProxyAuthUser = sec.Key("REVERSE_PROXY_AUTHENTICATION_USER").MustString("X-WEBAUTH-USER")
  865. ReverseProxyAuthEmail = sec.Key("REVERSE_PROXY_AUTHENTICATION_EMAIL").MustString("X-WEBAUTH-EMAIL")
  866. ReverseProxyAuthFullName = sec.Key("REVERSE_PROXY_AUTHENTICATION_FULL_NAME").MustString("X-WEBAUTH-FULLNAME")
  867. ReverseProxyLimit = sec.Key("REVERSE_PROXY_LIMIT").MustInt(1)
  868. ReverseProxyTrustedProxies = sec.Key("REVERSE_PROXY_TRUSTED_PROXIES").Strings(",")
  869. if len(ReverseProxyTrustedProxies) == 0 {
  870. ReverseProxyTrustedProxies = []string{"127.0.0.0/8", "::1/128"}
  871. }
  872. MinPasswordLength = sec.Key("MIN_PASSWORD_LENGTH").MustInt(6)
  873. ImportLocalPaths = sec.Key("IMPORT_LOCAL_PATHS").MustBool(false)
  874. DisableGitHooks = sec.Key("DISABLE_GIT_HOOKS").MustBool(true)
  875. DisableWebhooks = sec.Key("DISABLE_WEBHOOKS").MustBool(false)
  876. OnlyAllowPushIfGiteaEnvironmentSet = sec.Key("ONLY_ALLOW_PUSH_IF_GITEA_ENVIRONMENT_SET").MustBool(true)
  877. PasswordHashAlgo = sec.Key("PASSWORD_HASH_ALGO").MustString("pbkdf2")
  878. CSRFCookieHTTPOnly = sec.Key("CSRF_COOKIE_HTTP_ONLY").MustBool(true)
  879. PasswordCheckPwn = sec.Key("PASSWORD_CHECK_PWN").MustBool(false)
  880. SuccessfulTokensCacheSize = sec.Key("SUCCESSFUL_TOKENS_CACHE_SIZE").MustInt(20)
  881. InternalToken = loadSecret(sec, "INTERNAL_TOKEN_URI", "INTERNAL_TOKEN")
  882. if InstallLock && InternalToken == "" {
  883. // if Gitea has been installed but the InternalToken hasn't been generated (upgrade from an old release), we should generate
  884. // some users do cluster deployment, they still depend on this auto-generating behavior.
  885. generateSaveInternalToken()
  886. }
  887. cfgdata := sec.Key("PASSWORD_COMPLEXITY").Strings(",")
  888. if len(cfgdata) == 0 {
  889. cfgdata = []string{"off"}
  890. }
  891. PasswordComplexity = make([]string, 0, len(cfgdata))
  892. for _, name := range cfgdata {
  893. name := strings.ToLower(strings.Trim(name, `"`))
  894. if name != "" {
  895. PasswordComplexity = append(PasswordComplexity, name)
  896. }
  897. }
  898. newAttachmentService()
  899. newLFSService()
  900. timeFormatKey := Cfg.Section("time").Key("FORMAT").MustString("")
  901. if timeFormatKey != "" {
  902. TimeFormat = map[string]string{
  903. "ANSIC": time.ANSIC,
  904. "UnixDate": time.UnixDate,
  905. "RubyDate": time.RubyDate,
  906. "RFC822": time.RFC822,
  907. "RFC822Z": time.RFC822Z,
  908. "RFC850": time.RFC850,
  909. "RFC1123": time.RFC1123,
  910. "RFC1123Z": time.RFC1123Z,
  911. "RFC3339": time.RFC3339,
  912. "RFC3339Nano": time.RFC3339Nano,
  913. "Kitchen": time.Kitchen,
  914. "Stamp": time.Stamp,
  915. "StampMilli": time.StampMilli,
  916. "StampMicro": time.StampMicro,
  917. "StampNano": time.StampNano,
  918. }[timeFormatKey]
  919. // When the TimeFormatKey does not exist in the previous map e.g.'2006-01-02 15:04:05'
  920. if len(TimeFormat) == 0 {
  921. TimeFormat = timeFormatKey
  922. TestTimeFormat, _ := time.Parse(TimeFormat, TimeFormat)
  923. if TestTimeFormat.Format(time.RFC3339) != "2006-01-02T15:04:05Z" {
  924. log.Warn("Provided TimeFormat: %s does not create a fully specified date and time.", TimeFormat)
  925. log.Warn("In order to display dates and times correctly please check your time format has 2006, 01, 02, 15, 04 and 05")
  926. }
  927. log.Trace("Custom TimeFormat: %s", TimeFormat)
  928. }
  929. }
  930. zone := Cfg.Section("time").Key("DEFAULT_UI_LOCATION").String()
  931. if zone != "" {
  932. DefaultUILocation, err = time.LoadLocation(zone)
  933. if err != nil {
  934. log.Fatal("Load time zone failed: %v", err)
  935. } else {
  936. log.Info("Default UI Location is %v", zone)
  937. }
  938. }
  939. if DefaultUILocation == nil {
  940. DefaultUILocation = time.Local
  941. }
  942. RunUser = Cfg.Section("").Key("RUN_USER").MustString(user.CurrentUsername())
  943. // The following is a purposefully undocumented option. Please do not run Gitea as root. It will only cause future headaches.
  944. // Please don't use root as a bandaid to "fix" something that is broken, instead the broken thing should instead be fixed properly.
  945. unsafeAllowRunAsRoot := Cfg.Section("").Key("I_AM_BEING_UNSAFE_RUNNING_AS_ROOT").MustBool(false)
  946. RunMode = os.Getenv("GITEA_RUN_MODE")
  947. if RunMode == "" {
  948. RunMode = Cfg.Section("").Key("RUN_MODE").MustString("prod")
  949. }
  950. IsProd = strings.EqualFold(RunMode, "prod")
  951. // Does not check run user when the install lock is off.
  952. if InstallLock {
  953. currentUser, match := IsRunUserMatchCurrentUser(RunUser)
  954. if !match {
  955. log.Fatal("Expect user '%s' but current user is: %s", RunUser, currentUser)
  956. }
  957. }
  958. // check if we run as root
  959. if os.Getuid() == 0 {
  960. if !unsafeAllowRunAsRoot {
  961. // Special thanks to VLC which inspired the wording of this messaging.
  962. log.Fatal("Gitea is not supposed to be run as root. Sorry. If you need to use privileged TCP ports please instead use setcap and the `cap_net_bind_service` permission")
  963. }
  964. log.Critical("You are running Gitea using the root user, and have purposely chosen to skip built-in protections around this. You have been warned against this.")
  965. }
  966. SSH.BuiltinServerUser = Cfg.Section("server").Key("BUILTIN_SSH_SERVER_USER").MustString(RunUser)
  967. SSH.User = Cfg.Section("server").Key("SSH_USER").MustString(SSH.BuiltinServerUser)
  968. newRepository()
  969. newPictureService()
  970. newPackages()
  971. newActions()
  972. if err = Cfg.Section("ui").MapTo(&UI); err != nil {
  973. log.Fatal("Failed to map UI settings: %v", err)
  974. } else if err = Cfg.Section("markdown").MapTo(&Markdown); err != nil {
  975. log.Fatal("Failed to map Markdown settings: %v", err)
  976. } else if err = Cfg.Section("admin").MapTo(&Admin); err != nil {
  977. log.Fatal("Fail to map Admin settings: %v", err)
  978. } else if err = Cfg.Section("api").MapTo(&API); err != nil {
  979. log.Fatal("Failed to map API settings: %v", err)
  980. } else if err = Cfg.Section("metrics").MapTo(&Metrics); err != nil {
  981. log.Fatal("Failed to map Metrics settings: %v", err)
  982. } else if err = Cfg.Section("camo").MapTo(&Camo); err != nil {
  983. log.Fatal("Failed to map Camo settings: %v", err)
  984. }
  985. if Camo.Enabled {
  986. if Camo.ServerURL == "" || Camo.HMACKey == "" {
  987. log.Fatal(`Camo settings require "SERVER_URL" and HMAC_KEY`)
  988. }
  989. }
  990. u := *appURL
  991. u.Path = path.Join(u.Path, "api", "swagger")
  992. API.SwaggerURL = u.String()
  993. newGit()
  994. newMirror()
  995. Langs = Cfg.Section("i18n").Key("LANGS").Strings(",")
  996. if len(Langs) == 0 {
  997. Langs = defaultI18nLangs()
  998. }
  999. Names = Cfg.Section("i18n").Key("NAMES").Strings(",")
  1000. if len(Names) == 0 {
  1001. Names = defaultI18nNames()
  1002. }
  1003. ShowFooterBranding = Cfg.Section("other").Key("SHOW_FOOTER_BRANDING").MustBool(false)
  1004. ShowFooterVersion = Cfg.Section("other").Key("SHOW_FOOTER_VERSION").MustBool(true)
  1005. ShowFooterTemplateLoadTime = Cfg.Section("other").Key("SHOW_FOOTER_TEMPLATE_LOAD_TIME").MustBool(true)
  1006. EnableSitemap = Cfg.Section("other").Key("ENABLE_SITEMAP").MustBool(true)
  1007. EnableFeed = Cfg.Section("other").Key("ENABLE_FEED").MustBool(true)
  1008. UI.ShowUserEmail = Cfg.Section("ui").Key("SHOW_USER_EMAIL").MustBool(true)
  1009. UI.DefaultShowFullName = Cfg.Section("ui").Key("DEFAULT_SHOW_FULL_NAME").MustBool(false)
  1010. UI.SearchRepoDescription = Cfg.Section("ui").Key("SEARCH_REPO_DESCRIPTION").MustBool(true)
  1011. UI.UseServiceWorker = Cfg.Section("ui").Key("USE_SERVICE_WORKER").MustBool(false)
  1012. UI.OnlyShowRelevantRepos = Cfg.Section("ui").Key("ONLY_SHOW_RELEVANT_REPOS").MustBool(false)
  1013. HasRobotsTxt, err = util.IsFile(path.Join(CustomPath, "robots.txt"))
  1014. if err != nil {
  1015. log.Error("Unable to check if %s is a file. Error: %v", path.Join(CustomPath, "robots.txt"), err)
  1016. }
  1017. newMarkup()
  1018. UI.ReactionsLookup = make(container.Set[string])
  1019. for _, reaction := range UI.Reactions {
  1020. UI.ReactionsLookup.Add(reaction)
  1021. }
  1022. UI.CustomEmojisMap = make(map[string]string)
  1023. for _, emoji := range UI.CustomEmojis {
  1024. UI.CustomEmojisMap[emoji] = ":" + emoji + ":"
  1025. }
  1026. }
  1027. func parseAuthorizedPrincipalsAllow(values []string) ([]string, bool) {
  1028. anything := false
  1029. email := false
  1030. username := false
  1031. for _, value := range values {
  1032. v := strings.ToLower(strings.TrimSpace(value))
  1033. switch v {
  1034. case "off":
  1035. return []string{"off"}, false
  1036. case "email":
  1037. email = true
  1038. case "username":
  1039. username = true
  1040. case "anything":
  1041. anything = true
  1042. }
  1043. }
  1044. if anything {
  1045. return []string{"anything"}, true
  1046. }
  1047. authorizedPrincipalsAllow := []string{}
  1048. if username {
  1049. authorizedPrincipalsAllow = append(authorizedPrincipalsAllow, "username")
  1050. }
  1051. if email {
  1052. authorizedPrincipalsAllow = append(authorizedPrincipalsAllow, "email")
  1053. }
  1054. return authorizedPrincipalsAllow, true
  1055. }
  1056. // loadSecret load the secret from ini by uriKey or verbatimKey, only one of them could be set
  1057. // If the secret is loaded from uriKey (file), the file should be non-empty, to guarantee the behavior stable and clear.
  1058. func loadSecret(sec *ini.Section, uriKey, verbatimKey string) string {
  1059. // don't allow setting both URI and verbatim string
  1060. uri := sec.Key(uriKey).String()
  1061. verbatim := sec.Key(verbatimKey).String()
  1062. if uri != "" && verbatim != "" {
  1063. log.Fatal("Cannot specify both %s and %s", uriKey, verbatimKey)
  1064. }
  1065. // if we have no URI, use verbatim
  1066. if uri == "" {
  1067. return verbatim
  1068. }
  1069. tempURI, err := url.Parse(uri)
  1070. if err != nil {
  1071. log.Fatal("Failed to parse %s (%s): %v", uriKey, uri, err)
  1072. }
  1073. switch tempURI.Scheme {
  1074. case "file":
  1075. buf, err := os.ReadFile(tempURI.RequestURI())
  1076. if err != nil {
  1077. log.Fatal("Failed to read %s (%s): %v", uriKey, tempURI.RequestURI(), err)
  1078. }
  1079. val := strings.TrimSpace(string(buf))
  1080. if val == "" {
  1081. // The file shouldn't be empty, otherwise we can not know whether the user has ever set the KEY or KEY_URI
  1082. // For example: if INTERNAL_TOKEN_URI=file:///empty-file,
  1083. // Then if the token is re-generated during installation and saved to INTERNAL_TOKEN
  1084. // Then INTERNAL_TOKEN and INTERNAL_TOKEN_URI both exist, that's a fatal error (they shouldn't)
  1085. log.Fatal("Failed to read %s (%s): the file is empty", uriKey, tempURI.RequestURI())
  1086. }
  1087. return val
  1088. // only file URIs are allowed
  1089. default:
  1090. log.Fatal("Unsupported URI-Scheme %q (INTERNAL_TOKEN_URI = %q)", tempURI.Scheme, uri)
  1091. return ""
  1092. }
  1093. }
  1094. // generateSaveInternalToken generates and saves the internal token to app.ini
  1095. func generateSaveInternalToken() {
  1096. token, err := generate.NewInternalToken()
  1097. if err != nil {
  1098. log.Fatal("Error generate internal token: %v", err)
  1099. }
  1100. InternalToken = token
  1101. CreateOrAppendToCustomConf("security.INTERNAL_TOKEN", func(cfg *ini.File) {
  1102. cfg.Section("security").Key("INTERNAL_TOKEN").SetValue(token)
  1103. })
  1104. }
  1105. // MakeAbsoluteAssetURL returns the absolute asset url prefix without a trailing slash
  1106. func MakeAbsoluteAssetURL(appURL, staticURLPrefix string) string {
  1107. parsedPrefix, err := url.Parse(strings.TrimSuffix(staticURLPrefix, "/"))
  1108. if err != nil {
  1109. log.Fatal("Unable to parse STATIC_URL_PREFIX: %v", err)
  1110. }
  1111. if err == nil && parsedPrefix.Hostname() == "" {
  1112. if staticURLPrefix == "" {
  1113. return strings.TrimSuffix(appURL, "/")
  1114. }
  1115. // StaticURLPrefix is just a path
  1116. return util.URLJoin(appURL, strings.TrimSuffix(staticURLPrefix, "/"))
  1117. }
  1118. return strings.TrimSuffix(staticURLPrefix, "/")
  1119. }
  1120. // MakeManifestData generates web app manifest JSON
  1121. func MakeManifestData(appName, appURL, absoluteAssetURL string) []byte {
  1122. type manifestIcon struct {
  1123. Src string `json:"src"`
  1124. Type string `json:"type"`
  1125. Sizes string `json:"sizes"`
  1126. }
  1127. type manifestJSON struct {
  1128. Name string `json:"name"`
  1129. ShortName string `json:"short_name"`
  1130. StartURL string `json:"start_url"`
  1131. Icons []manifestIcon `json:"icons"`
  1132. }
  1133. bytes, err := json.Marshal(&manifestJSON{
  1134. Name: appName,
  1135. ShortName: appName,
  1136. StartURL: appURL,
  1137. Icons: []manifestIcon{
  1138. {
  1139. Src: absoluteAssetURL + "/assets/img/logo.png",
  1140. Type: "image/png",
  1141. Sizes: "512x512",
  1142. },
  1143. {
  1144. Src: absoluteAssetURL + "/assets/img/logo.svg",
  1145. Type: "image/svg+xml",
  1146. Sizes: "512x512",
  1147. },
  1148. },
  1149. })
  1150. if err != nil {
  1151. log.Error("unable to marshal manifest JSON. Error: %v", err)
  1152. return make([]byte, 0)
  1153. }
  1154. return bytes
  1155. }
  1156. // CreateOrAppendToCustomConf creates or updates the custom config.
  1157. // Use the callback to set individual values.
  1158. func CreateOrAppendToCustomConf(purpose string, callback func(cfg *ini.File)) {
  1159. if CustomConf == "" {
  1160. log.Error("Custom config path must not be empty")
  1161. return
  1162. }
  1163. cfg := ini.Empty()
  1164. isFile, err := util.IsFile(CustomConf)
  1165. if err != nil {
  1166. log.Error("Unable to check if %s is a file. Error: %v", CustomConf, err)
  1167. }
  1168. if isFile {
  1169. if err := cfg.Append(CustomConf); err != nil {
  1170. log.Error("failed to load custom conf %s: %v", CustomConf, err)
  1171. return
  1172. }
  1173. }
  1174. callback(cfg)
  1175. if err := os.MkdirAll(filepath.Dir(CustomConf), os.ModePerm); err != nil {
  1176. log.Fatal("failed to create '%s': %v", CustomConf, err)
  1177. return
  1178. }
  1179. if err := cfg.SaveTo(CustomConf); err != nil {
  1180. log.Fatal("error saving to custom config: %v", err)
  1181. }
  1182. log.Info("Settings for %s saved to: %q", purpose, CustomConf)
  1183. // Change permissions to be more restrictive
  1184. fi, err := os.Stat(CustomConf)
  1185. if err != nil {
  1186. log.Error("Failed to determine current conf file permissions: %v", err)
  1187. return
  1188. }
  1189. if fi.Mode().Perm() > 0o600 {
  1190. if err = os.Chmod(CustomConf, 0o600); err != nil {
  1191. log.Warn("Failed changing conf file permissions to -rw-------. Consider changing them manually.")
  1192. }
  1193. }
  1194. }
  1195. // NewServices initializes the services
  1196. func NewServices() {
  1197. InitDBConfig()
  1198. newService()
  1199. newOAuth2Client()
  1200. NewLogServices(false)
  1201. newCacheService()
  1202. newSessionService()
  1203. newCORSService()
  1204. parseMailerConfig(Cfg)
  1205. newIncomingEmail()
  1206. newRegisterMailService()
  1207. newNotifyMailService()
  1208. newProxyService()
  1209. newWebhookService()
  1210. newMigrationsService()
  1211. newIndexerService()
  1212. newTaskService()
  1213. NewQueueService()
  1214. newProject()
  1215. newMimeTypeMap()
  1216. newFederationService()
  1217. }
  1218. // NewServicesForInstall initializes the services for install
  1219. func NewServicesForInstall() {
  1220. newService()
  1221. parseMailerConfig(Cfg)
  1222. }