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 42KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2017 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package setting
  6. import (
  7. "encoding/base64"
  8. "fmt"
  9. "io"
  10. "math"
  11. "net"
  12. "net/url"
  13. "os"
  14. "os/exec"
  15. "path"
  16. "path/filepath"
  17. "runtime"
  18. "strconv"
  19. "strings"
  20. "text/template"
  21. "time"
  22. "code.gitea.io/gitea/modules/generate"
  23. "code.gitea.io/gitea/modules/json"
  24. "code.gitea.io/gitea/modules/log"
  25. "code.gitea.io/gitea/modules/user"
  26. "code.gitea.io/gitea/modules/util"
  27. shellquote "github.com/kballard/go-shellquote"
  28. "github.com/unknwon/com"
  29. gossh "golang.org/x/crypto/ssh"
  30. ini "gopkg.in/ini.v1"
  31. )
  32. // Scheme describes protocol types
  33. type Scheme string
  34. // enumerates all the scheme types
  35. const (
  36. HTTP Scheme = "http"
  37. HTTPS Scheme = "https"
  38. FCGI Scheme = "fcgi"
  39. FCGIUnix Scheme = "fcgi+unix"
  40. UnixSocket Scheme = "unix"
  41. )
  42. // LandingPage describes the default page
  43. type LandingPage string
  44. // enumerates all the landing page types
  45. const (
  46. LandingPageHome LandingPage = "/"
  47. LandingPageExplore LandingPage = "/explore"
  48. LandingPageOrganizations LandingPage = "/explore/organizations"
  49. LandingPageLogin LandingPage = "/user/login"
  50. )
  51. // enumerates all the types of captchas
  52. const (
  53. ImageCaptcha = "image"
  54. ReCaptcha = "recaptcha"
  55. HCaptcha = "hcaptcha"
  56. )
  57. // settings
  58. var (
  59. // AppVer is the version of the current build of Gitea. It is set in main.go from main.Version.
  60. AppVer string
  61. // AppBuiltWith represents a human readable version go runtime build version and build tags. (See main.go formatBuiltWith().)
  62. AppBuiltWith string
  63. // AppStartTime store time gitea has started
  64. AppStartTime time.Time
  65. // AppName is the Application name, used in the page title.
  66. // It maps to ini:"APP_NAME"
  67. AppName string
  68. // AppURL is the Application ROOT_URL. It always has a '/' suffix
  69. // It maps to ini:"ROOT_URL"
  70. AppURL string
  71. // AppSubURL represents the sub-url mounting point for gitea. It is either "" or starts with '/' and ends without '/', such as '/{subpath}'.
  72. // This value is empty if site does not have sub-url.
  73. AppSubURL string
  74. // AppPath represents the path to the gitea binary
  75. AppPath string
  76. // AppWorkPath is the "working directory" of Gitea. It maps to the environment variable GITEA_WORK_DIR.
  77. // If that is not set it is the default set here by the linker or failing that the directory of AppPath.
  78. //
  79. // AppWorkPath is used as the base path for several other paths.
  80. AppWorkPath string
  81. // AppDataPath is the default path for storing data.
  82. // It maps to ini:"APP_DATA_PATH" and defaults to AppWorkPath + "/data"
  83. AppDataPath string
  84. // Server settings
  85. Protocol Scheme
  86. Domain string
  87. HTTPAddr string
  88. HTTPPort string
  89. LocalURL string
  90. RedirectOtherPort bool
  91. PortToRedirect string
  92. OfflineMode bool
  93. CertFile string
  94. KeyFile string
  95. StaticRootPath string
  96. StaticCacheTime time.Duration
  97. EnableGzip bool
  98. LandingPageURL LandingPage
  99. UnixSocketPermission uint32
  100. EnablePprof bool
  101. PprofDataPath string
  102. EnableLetsEncrypt bool
  103. LetsEncryptTOS bool
  104. LetsEncryptDirectory string
  105. LetsEncryptEmail string
  106. SSLMinimumVersion string
  107. SSLMaximumVersion string
  108. SSLCurvePreferences []string
  109. SSLCipherSuites []string
  110. GracefulRestartable bool
  111. GracefulHammerTime time.Duration
  112. StartupTimeout time.Duration
  113. PerWriteTimeout = 30 * time.Second
  114. PerWritePerKbTimeout = 10 * time.Second
  115. StaticURLPrefix string
  116. AbsoluteAssetURL string
  117. SSH = struct {
  118. Disabled bool `ini:"DISABLE_SSH"`
  119. StartBuiltinServer bool `ini:"START_SSH_SERVER"`
  120. BuiltinServerUser string `ini:"BUILTIN_SSH_SERVER_USER"`
  121. Domain string `ini:"SSH_DOMAIN"`
  122. Port int `ini:"SSH_PORT"`
  123. ListenHost string `ini:"SSH_LISTEN_HOST"`
  124. ListenPort int `ini:"SSH_LISTEN_PORT"`
  125. RootPath string `ini:"SSH_ROOT_PATH"`
  126. ServerCiphers []string `ini:"SSH_SERVER_CIPHERS"`
  127. ServerKeyExchanges []string `ini:"SSH_SERVER_KEY_EXCHANGES"`
  128. ServerMACs []string `ini:"SSH_SERVER_MACS"`
  129. ServerHostKeys []string `ini:"SSH_SERVER_HOST_KEYS"`
  130. KeyTestPath string `ini:"SSH_KEY_TEST_PATH"`
  131. KeygenPath string `ini:"SSH_KEYGEN_PATH"`
  132. AuthorizedKeysBackup bool `ini:"SSH_AUTHORIZED_KEYS_BACKUP"`
  133. AuthorizedPrincipalsBackup bool `ini:"SSH_AUTHORIZED_PRINCIPALS_BACKUP"`
  134. AuthorizedKeysCommandTemplate string `ini:"SSH_AUTHORIZED_KEYS_COMMAND_TEMPLATE"`
  135. AuthorizedKeysCommandTemplateTemplate *template.Template `ini:"-"`
  136. MinimumKeySizeCheck bool `ini:"-"`
  137. MinimumKeySizes map[string]int `ini:"-"`
  138. CreateAuthorizedKeysFile bool `ini:"SSH_CREATE_AUTHORIZED_KEYS_FILE"`
  139. CreateAuthorizedPrincipalsFile bool `ini:"SSH_CREATE_AUTHORIZED_PRINCIPALS_FILE"`
  140. ExposeAnonymous bool `ini:"SSH_EXPOSE_ANONYMOUS"`
  141. AuthorizedPrincipalsAllow []string `ini:"SSH_AUTHORIZED_PRINCIPALS_ALLOW"`
  142. AuthorizedPrincipalsEnabled bool `ini:"-"`
  143. TrustedUserCAKeys []string `ini:"SSH_TRUSTED_USER_CA_KEYS"`
  144. TrustedUserCAKeysFile string `ini:"SSH_TRUSTED_USER_CA_KEYS_FILENAME"`
  145. TrustedUserCAKeysParsed []gossh.PublicKey `ini:"-"`
  146. PerWriteTimeout time.Duration `ini:"SSH_PER_WRITE_TIMEOUT"`
  147. PerWritePerKbTimeout time.Duration `ini:"SSH_PER_WRITE_PER_KB_TIMEOUT"`
  148. }{
  149. Disabled: false,
  150. StartBuiltinServer: false,
  151. Domain: "",
  152. Port: 22,
  153. ServerCiphers: []string{"aes128-ctr", "aes192-ctr", "aes256-ctr", "aes128-gcm@openssh.com", "arcfour256", "arcfour128"},
  154. ServerKeyExchanges: []string{"diffie-hellman-group1-sha1", "diffie-hellman-group14-sha1", "ecdh-sha2-nistp256", "ecdh-sha2-nistp384", "ecdh-sha2-nistp521", "curve25519-sha256@libssh.org"},
  155. ServerMACs: []string{"hmac-sha2-256-etm@openssh.com", "hmac-sha2-256", "hmac-sha1", "hmac-sha1-96"},
  156. KeygenPath: "ssh-keygen",
  157. MinimumKeySizeCheck: true,
  158. MinimumKeySizes: map[string]int{"ed25519": 256, "ed25519-sk": 256, "ecdsa": 256, "ecdsa-sk": 256, "rsa": 2048},
  159. ServerHostKeys: []string{"ssh/gitea.rsa", "ssh/gogs.rsa"},
  160. AuthorizedKeysCommandTemplate: "{{.AppPath}} --config={{.CustomConf}} serv key-{{.Key.ID}}",
  161. PerWriteTimeout: PerWriteTimeout,
  162. PerWritePerKbTimeout: PerWritePerKbTimeout,
  163. }
  164. // Security settings
  165. InstallLock bool
  166. SecretKey string
  167. LogInRememberDays int
  168. CookieUserName string
  169. CookieRememberName string
  170. ReverseProxyAuthUser string
  171. ReverseProxyAuthEmail string
  172. ReverseProxyLimit int
  173. ReverseProxyTrustedProxies []string
  174. MinPasswordLength int
  175. ImportLocalPaths bool
  176. DisableGitHooks bool
  177. DisableWebhooks bool
  178. OnlyAllowPushIfGiteaEnvironmentSet bool
  179. PasswordComplexity []string
  180. PasswordHashAlgo string
  181. PasswordCheckPwn bool
  182. SuccessfulTokensCacheSize int
  183. // UI settings
  184. UI = struct {
  185. ExplorePagingNum int
  186. IssuePagingNum int
  187. RepoSearchPagingNum int
  188. MembersPagingNum int
  189. FeedMaxCommitNum int
  190. FeedPagingNum int
  191. GraphMaxCommitNum int
  192. CodeCommentLines int
  193. ReactionMaxUserNum int
  194. ThemeColorMetaTag string
  195. MaxDisplayFileSize int64
  196. ShowUserEmail bool
  197. DefaultShowFullName bool
  198. DefaultTheme string
  199. Themes []string
  200. Reactions []string
  201. ReactionsMap map[string]bool `ini:"-"`
  202. CustomEmojis []string
  203. CustomEmojisMap map[string]string `ini:"-"`
  204. SearchRepoDescription bool
  205. UseServiceWorker bool
  206. Notification struct {
  207. MinTimeout time.Duration
  208. TimeoutStep time.Duration
  209. MaxTimeout time.Duration
  210. EventSourceUpdateTime time.Duration
  211. } `ini:"ui.notification"`
  212. SVG struct {
  213. Enabled bool `ini:"ENABLE_RENDER"`
  214. } `ini:"ui.svg"`
  215. CSV struct {
  216. MaxFileSize int64
  217. } `ini:"ui.csv"`
  218. Admin struct {
  219. UserPagingNum int
  220. RepoPagingNum int
  221. NoticePagingNum int
  222. OrgPagingNum int
  223. } `ini:"ui.admin"`
  224. User struct {
  225. RepoPagingNum int
  226. } `ini:"ui.user"`
  227. Meta struct {
  228. Author string
  229. Description string
  230. Keywords string
  231. } `ini:"ui.meta"`
  232. }{
  233. ExplorePagingNum: 20,
  234. IssuePagingNum: 10,
  235. RepoSearchPagingNum: 10,
  236. MembersPagingNum: 20,
  237. FeedMaxCommitNum: 5,
  238. FeedPagingNum: 20,
  239. GraphMaxCommitNum: 100,
  240. CodeCommentLines: 4,
  241. ReactionMaxUserNum: 10,
  242. ThemeColorMetaTag: `#6cc644`,
  243. MaxDisplayFileSize: 8388608,
  244. DefaultTheme: `auto`,
  245. Themes: []string{`auto`, `gitea`, `arc-green`},
  246. Reactions: []string{`+1`, `-1`, `laugh`, `hooray`, `confused`, `heart`, `rocket`, `eyes`},
  247. CustomEmojis: []string{`git`, `gitea`, `codeberg`, `gitlab`, `github`, `gogs`},
  248. CustomEmojisMap: map[string]string{"git": ":git:", "gitea": ":gitea:", "codeberg": ":codeberg:", "gitlab": ":gitlab:", "github": ":github:", "gogs": ":gogs:"},
  249. Notification: struct {
  250. MinTimeout time.Duration
  251. TimeoutStep time.Duration
  252. MaxTimeout time.Duration
  253. EventSourceUpdateTime time.Duration
  254. }{
  255. MinTimeout: 10 * time.Second,
  256. TimeoutStep: 10 * time.Second,
  257. MaxTimeout: 60 * time.Second,
  258. EventSourceUpdateTime: 10 * time.Second,
  259. },
  260. SVG: struct {
  261. Enabled bool `ini:"ENABLE_RENDER"`
  262. }{
  263. Enabled: true,
  264. },
  265. CSV: struct {
  266. MaxFileSize int64
  267. }{
  268. MaxFileSize: 524288,
  269. },
  270. Admin: struct {
  271. UserPagingNum int
  272. RepoPagingNum int
  273. NoticePagingNum int
  274. OrgPagingNum int
  275. }{
  276. UserPagingNum: 50,
  277. RepoPagingNum: 50,
  278. NoticePagingNum: 25,
  279. OrgPagingNum: 50,
  280. },
  281. User: struct {
  282. RepoPagingNum int
  283. }{
  284. RepoPagingNum: 15,
  285. },
  286. Meta: struct {
  287. Author string
  288. Description string
  289. Keywords string
  290. }{
  291. Author: "Gitea - Git with a cup of tea",
  292. Description: "Gitea (Git with a cup of tea) is a painless self-hosted Git service written in Go",
  293. Keywords: "go,git,self-hosted,gitea",
  294. },
  295. }
  296. // Markdown settings
  297. Markdown = struct {
  298. EnableHardLineBreakInComments bool
  299. EnableHardLineBreakInDocuments bool
  300. CustomURLSchemes []string `ini:"CUSTOM_URL_SCHEMES"`
  301. FileExtensions []string
  302. }{
  303. EnableHardLineBreakInComments: true,
  304. EnableHardLineBreakInDocuments: false,
  305. FileExtensions: strings.Split(".md,.markdown,.mdown,.mkd", ","),
  306. }
  307. // Admin settings
  308. Admin struct {
  309. DisableRegularOrgCreation bool
  310. DefaultEmailNotification string
  311. }
  312. // Log settings
  313. LogLevel log.Level
  314. StacktraceLogLevel string
  315. LogRootPath string
  316. DisableRouterLog bool
  317. RouterLogLevel log.Level
  318. EnableAccessLog bool
  319. EnableSSHLog bool
  320. AccessLogTemplate string
  321. EnableXORMLog bool
  322. // Time settings
  323. TimeFormat string
  324. // UILocation is the location on the UI, so that we can display the time on UI.
  325. DefaultUILocation = time.Local
  326. CSRFCookieName = "_csrf"
  327. CSRFCookieHTTPOnly = true
  328. ManifestData string
  329. // API settings
  330. API = struct {
  331. EnableSwagger bool
  332. SwaggerURL string
  333. MaxResponseItems int
  334. DefaultPagingNum int
  335. DefaultGitTreesPerPage int
  336. DefaultMaxBlobSize int64
  337. }{
  338. EnableSwagger: true,
  339. SwaggerURL: "",
  340. MaxResponseItems: 50,
  341. DefaultPagingNum: 30,
  342. DefaultGitTreesPerPage: 1000,
  343. DefaultMaxBlobSize: 10485760,
  344. }
  345. OAuth2 = struct {
  346. Enable bool
  347. AccessTokenExpirationTime int64
  348. RefreshTokenExpirationTime int64
  349. InvalidateRefreshTokens bool
  350. JWTSigningAlgorithm string `ini:"JWT_SIGNING_ALGORITHM"`
  351. JWTSecretBase64 string `ini:"JWT_SECRET"`
  352. JWTSigningPrivateKeyFile string `ini:"JWT_SIGNING_PRIVATE_KEY_FILE"`
  353. MaxTokenLength int
  354. }{
  355. Enable: true,
  356. AccessTokenExpirationTime: 3600,
  357. RefreshTokenExpirationTime: 730,
  358. InvalidateRefreshTokens: false,
  359. JWTSigningAlgorithm: "RS256",
  360. JWTSigningPrivateKeyFile: "jwt/private.pem",
  361. MaxTokenLength: math.MaxInt16,
  362. }
  363. U2F = struct {
  364. AppID string
  365. TrustedFacets []string
  366. }{}
  367. // Metrics settings
  368. Metrics = struct {
  369. Enabled bool
  370. Token string
  371. EnabledIssueByLabel bool
  372. EnabledIssueByRepository bool
  373. }{
  374. Enabled: false,
  375. Token: "",
  376. EnabledIssueByLabel: false,
  377. EnabledIssueByRepository: false,
  378. }
  379. // I18n settings
  380. Langs []string
  381. Names []string
  382. // Highlight settings are loaded in modules/template/highlight.go
  383. // Other settings
  384. ShowFooterBranding bool
  385. ShowFooterVersion bool
  386. ShowFooterTemplateLoadTime bool
  387. // Global setting objects
  388. Cfg *ini.File
  389. CustomPath string // Custom directory path
  390. CustomConf string
  391. PIDFile = "/run/gitea.pid"
  392. WritePIDFile bool
  393. RunMode string
  394. IsProd bool
  395. RunUser string
  396. IsWindows bool
  397. HasRobotsTxt bool
  398. InternalToken string // internal access token
  399. )
  400. func getAppPath() (string, error) {
  401. var appPath string
  402. var err error
  403. if IsWindows && filepath.IsAbs(os.Args[0]) {
  404. appPath = filepath.Clean(os.Args[0])
  405. } else {
  406. appPath, err = exec.LookPath(os.Args[0])
  407. }
  408. if err != nil {
  409. return "", err
  410. }
  411. appPath, err = filepath.Abs(appPath)
  412. if err != nil {
  413. return "", err
  414. }
  415. // Note: we don't use path.Dir here because it does not handle case
  416. // which path starts with two "/" in Windows: "//psf/Home/..."
  417. return strings.ReplaceAll(appPath, "\\", "/"), err
  418. }
  419. func getWorkPath(appPath string) string {
  420. workPath := AppWorkPath
  421. if giteaWorkPath, ok := os.LookupEnv("GITEA_WORK_DIR"); ok {
  422. workPath = giteaWorkPath
  423. }
  424. if len(workPath) == 0 {
  425. i := strings.LastIndex(appPath, "/")
  426. if i == -1 {
  427. workPath = appPath
  428. } else {
  429. workPath = appPath[:i]
  430. }
  431. }
  432. return strings.ReplaceAll(workPath, "\\", "/")
  433. }
  434. func init() {
  435. IsWindows = runtime.GOOS == "windows"
  436. // We can rely on log.CanColorStdout being set properly because modules/log/console_windows.go comes before modules/setting/setting.go lexicographically
  437. // By default set this logger at Info - we'll change it later but we need to start with something.
  438. log.NewLogger(0, "console", "console", fmt.Sprintf(`{"level": "info", "colorize": %t, "stacktraceLevel": "none"}`, log.CanColorStdout))
  439. var err error
  440. if AppPath, err = getAppPath(); err != nil {
  441. log.Fatal("Failed to get app path: %v", err)
  442. }
  443. AppWorkPath = getWorkPath(AppPath)
  444. }
  445. func forcePathSeparator(path string) {
  446. if strings.Contains(path, "\\") {
  447. log.Fatal("Do not use '\\' or '\\\\' in paths, instead, please use '/' in all places")
  448. }
  449. }
  450. // IsRunUserMatchCurrentUser returns false if configured run user does not match
  451. // actual user that runs the app. The first return value is the actual user name.
  452. // This check is ignored under Windows since SSH remote login is not the main
  453. // method to login on Windows.
  454. func IsRunUserMatchCurrentUser(runUser string) (string, bool) {
  455. if IsWindows || SSH.StartBuiltinServer {
  456. return "", true
  457. }
  458. currentUser := user.CurrentUsername()
  459. return currentUser, runUser == currentUser
  460. }
  461. func createPIDFile(pidPath string) {
  462. currentPid := os.Getpid()
  463. if err := os.MkdirAll(filepath.Dir(pidPath), os.ModePerm); err != nil {
  464. log.Fatal("Failed to create PID folder: %v", err)
  465. }
  466. file, err := os.Create(pidPath)
  467. if err != nil {
  468. log.Fatal("Failed to create PID file: %v", err)
  469. }
  470. defer file.Close()
  471. if _, err := file.WriteString(strconv.FormatInt(int64(currentPid), 10)); err != nil {
  472. log.Fatal("Failed to write PID information: %v", err)
  473. }
  474. }
  475. // SetCustomPathAndConf will set CustomPath and CustomConf with reference to the
  476. // GITEA_CUSTOM environment variable and with provided overrides before stepping
  477. // back to the default
  478. func SetCustomPathAndConf(providedCustom, providedConf, providedWorkPath string) {
  479. if len(providedWorkPath) != 0 {
  480. AppWorkPath = filepath.ToSlash(providedWorkPath)
  481. }
  482. if giteaCustom, ok := os.LookupEnv("GITEA_CUSTOM"); ok {
  483. CustomPath = giteaCustom
  484. }
  485. if len(providedCustom) != 0 {
  486. CustomPath = providedCustom
  487. }
  488. if len(CustomPath) == 0 {
  489. CustomPath = path.Join(AppWorkPath, "custom")
  490. } else if !filepath.IsAbs(CustomPath) {
  491. CustomPath = path.Join(AppWorkPath, CustomPath)
  492. }
  493. if len(providedConf) != 0 {
  494. CustomConf = providedConf
  495. }
  496. if len(CustomConf) == 0 {
  497. CustomConf = path.Join(CustomPath, "conf/app.ini")
  498. } else if !filepath.IsAbs(CustomConf) {
  499. CustomConf = path.Join(CustomPath, CustomConf)
  500. log.Warn("Using 'custom' directory as relative origin for configuration file: '%s'", CustomConf)
  501. }
  502. }
  503. // NewContext initializes configuration context.
  504. // NOTE: do not print any log except error.
  505. func NewContext() {
  506. Cfg = ini.Empty()
  507. if WritePIDFile && len(PIDFile) > 0 {
  508. createPIDFile(PIDFile)
  509. }
  510. isFile, err := util.IsFile(CustomConf)
  511. if err != nil {
  512. log.Error("Unable to check if %s is a file. Error: %v", CustomConf, err)
  513. }
  514. if isFile {
  515. if err := Cfg.Append(CustomConf); err != nil {
  516. log.Fatal("Failed to load custom conf '%s': %v", CustomConf, err)
  517. }
  518. } else {
  519. log.Warn("Custom config '%s' not found, ignore this if you're running first time", CustomConf)
  520. }
  521. Cfg.NameMapper = ini.SnackCase
  522. homeDir, err := com.HomeDir()
  523. if err != nil {
  524. log.Fatal("Failed to get home directory: %v", err)
  525. }
  526. homeDir = strings.ReplaceAll(homeDir, "\\", "/")
  527. LogLevel = getLogLevel(Cfg.Section("log"), "LEVEL", log.INFO)
  528. StacktraceLogLevel = getStacktraceLogLevel(Cfg.Section("log"), "STACKTRACE_LEVEL", "None")
  529. LogRootPath = Cfg.Section("log").Key("ROOT_PATH").MustString(path.Join(AppWorkPath, "log"))
  530. forcePathSeparator(LogRootPath)
  531. RouterLogLevel = log.FromString(Cfg.Section("log").Key("ROUTER_LOG_LEVEL").MustString("Info"))
  532. sec := Cfg.Section("server")
  533. AppName = Cfg.Section("").Key("APP_NAME").MustString("Gitea: Git with a cup of tea")
  534. Protocol = HTTP
  535. switch sec.Key("PROTOCOL").String() {
  536. case "https":
  537. Protocol = HTTPS
  538. CertFile = sec.Key("CERT_FILE").String()
  539. KeyFile = sec.Key("KEY_FILE").String()
  540. if !filepath.IsAbs(CertFile) && len(CertFile) > 0 {
  541. CertFile = filepath.Join(CustomPath, CertFile)
  542. }
  543. if !filepath.IsAbs(KeyFile) && len(KeyFile) > 0 {
  544. KeyFile = filepath.Join(CustomPath, KeyFile)
  545. }
  546. case "fcgi":
  547. Protocol = FCGI
  548. case "fcgi+unix":
  549. Protocol = FCGIUnix
  550. UnixSocketPermissionRaw := sec.Key("UNIX_SOCKET_PERMISSION").MustString("666")
  551. UnixSocketPermissionParsed, err := strconv.ParseUint(UnixSocketPermissionRaw, 8, 32)
  552. if err != nil || UnixSocketPermissionParsed > 0777 {
  553. log.Fatal("Failed to parse unixSocketPermission: %s", UnixSocketPermissionRaw)
  554. }
  555. UnixSocketPermission = uint32(UnixSocketPermissionParsed)
  556. case "unix":
  557. Protocol = UnixSocket
  558. UnixSocketPermissionRaw := sec.Key("UNIX_SOCKET_PERMISSION").MustString("666")
  559. UnixSocketPermissionParsed, err := strconv.ParseUint(UnixSocketPermissionRaw, 8, 32)
  560. if err != nil || UnixSocketPermissionParsed > 0777 {
  561. log.Fatal("Failed to parse unixSocketPermission: %s", UnixSocketPermissionRaw)
  562. }
  563. UnixSocketPermission = uint32(UnixSocketPermissionParsed)
  564. }
  565. EnableLetsEncrypt = sec.Key("ENABLE_LETSENCRYPT").MustBool(false)
  566. LetsEncryptTOS = sec.Key("LETSENCRYPT_ACCEPTTOS").MustBool(false)
  567. if !LetsEncryptTOS && EnableLetsEncrypt {
  568. log.Warn("Failed to enable Let's Encrypt due to Let's Encrypt TOS not being accepted")
  569. EnableLetsEncrypt = false
  570. }
  571. LetsEncryptDirectory = sec.Key("LETSENCRYPT_DIRECTORY").MustString("https")
  572. LetsEncryptEmail = sec.Key("LETSENCRYPT_EMAIL").MustString("")
  573. SSLMinimumVersion = sec.Key("SSL_MIN_VERSION").MustString("")
  574. SSLMaximumVersion = sec.Key("SSL_MAX_VERSION").MustString("")
  575. SSLCurvePreferences = sec.Key("SSL_CURVE_PREFERENCES").Strings(",")
  576. SSLCipherSuites = sec.Key("SSL_CIPHER_SUITES").Strings(",")
  577. Domain = sec.Key("DOMAIN").MustString("localhost")
  578. HTTPAddr = sec.Key("HTTP_ADDR").MustString("0.0.0.0")
  579. HTTPPort = sec.Key("HTTP_PORT").MustString("3000")
  580. GracefulRestartable = sec.Key("ALLOW_GRACEFUL_RESTARTS").MustBool(true)
  581. GracefulHammerTime = sec.Key("GRACEFUL_HAMMER_TIME").MustDuration(60 * time.Second)
  582. StartupTimeout = sec.Key("STARTUP_TIMEOUT").MustDuration(0 * time.Second)
  583. PerWriteTimeout = sec.Key("PER_WRITE_TIMEOUT").MustDuration(PerWriteTimeout)
  584. PerWritePerKbTimeout = sec.Key("PER_WRITE_PER_KB_TIMEOUT").MustDuration(PerWritePerKbTimeout)
  585. defaultAppURL := string(Protocol) + "://" + Domain
  586. if (Protocol == HTTP && HTTPPort != "80") || (Protocol == HTTPS && HTTPPort != "443") {
  587. defaultAppURL += ":" + HTTPPort
  588. }
  589. AppURL = sec.Key("ROOT_URL").MustString(defaultAppURL + "/")
  590. // This should be TrimRight to ensure that there is only a single '/' at the end of AppURL.
  591. AppURL = strings.TrimRight(AppURL, "/") + "/"
  592. // Check if has app suburl.
  593. appURL, err := url.Parse(AppURL)
  594. if err != nil {
  595. log.Fatal("Invalid ROOT_URL '%s': %s", AppURL, err)
  596. }
  597. // Suburl should start with '/' and end without '/', such as '/{subpath}'.
  598. // This value is empty if site does not have sub-url.
  599. AppSubURL = strings.TrimSuffix(appURL.Path, "/")
  600. StaticURLPrefix = strings.TrimSuffix(sec.Key("STATIC_URL_PREFIX").MustString(AppSubURL), "/")
  601. // Check if Domain differs from AppURL domain than update it to AppURL's domain
  602. urlHostname := appURL.Hostname()
  603. if urlHostname != Domain && net.ParseIP(urlHostname) == nil && urlHostname != "" {
  604. Domain = urlHostname
  605. }
  606. AbsoluteAssetURL = MakeAbsoluteAssetURL(AppURL, StaticURLPrefix)
  607. manifestBytes := MakeManifestData(AppName, AppURL, AbsoluteAssetURL)
  608. ManifestData = `application/json;base64,` + base64.StdEncoding.EncodeToString(manifestBytes)
  609. var defaultLocalURL string
  610. switch Protocol {
  611. case UnixSocket:
  612. defaultLocalURL = "http://unix/"
  613. case FCGI:
  614. defaultLocalURL = AppURL
  615. case FCGIUnix:
  616. defaultLocalURL = AppURL
  617. default:
  618. defaultLocalURL = string(Protocol) + "://"
  619. if HTTPAddr == "0.0.0.0" {
  620. defaultLocalURL += net.JoinHostPort("localhost", HTTPPort) + "/"
  621. } else {
  622. defaultLocalURL += net.JoinHostPort(HTTPAddr, HTTPPort) + "/"
  623. }
  624. }
  625. LocalURL = sec.Key("LOCAL_ROOT_URL").MustString(defaultLocalURL)
  626. RedirectOtherPort = sec.Key("REDIRECT_OTHER_PORT").MustBool(false)
  627. PortToRedirect = sec.Key("PORT_TO_REDIRECT").MustString("80")
  628. OfflineMode = sec.Key("OFFLINE_MODE").MustBool()
  629. DisableRouterLog = sec.Key("DISABLE_ROUTER_LOG").MustBool()
  630. if len(StaticRootPath) == 0 {
  631. StaticRootPath = AppWorkPath
  632. }
  633. StaticRootPath = sec.Key("STATIC_ROOT_PATH").MustString(StaticRootPath)
  634. StaticCacheTime = sec.Key("STATIC_CACHE_TIME").MustDuration(6 * time.Hour)
  635. AppDataPath = sec.Key("APP_DATA_PATH").MustString(path.Join(AppWorkPath, "data"))
  636. if _, err = os.Stat(AppDataPath); err != nil {
  637. // FIXME: There are too many calls to MkdirAll in old code. It is incorrect.
  638. // For example, if someDir=/mnt/vol1/gitea-home/data, if the mount point /mnt/vol1 is not mounted when Gitea runs,
  639. // then gitea will make new empty directories in /mnt/vol1, all are stored in the root filesystem.
  640. // The correct behavior should be: creating parent directories is end users' duty. We only create sub-directories in existing parent directories.
  641. // For quickstart, the parent directories should be created automatically for first startup (eg: a flag or a check of INSTALL_LOCK).
  642. // Now we can take the first step to do correctly (using Mkdir) in other packages, and prepare the AppDataPath here, then make a refactor in future.
  643. err = os.MkdirAll(AppDataPath, os.ModePerm)
  644. if err != nil {
  645. log.Fatal("Failed to create the directory for app data path '%s'", AppDataPath)
  646. }
  647. }
  648. EnableGzip = sec.Key("ENABLE_GZIP").MustBool()
  649. EnablePprof = sec.Key("ENABLE_PPROF").MustBool(false)
  650. PprofDataPath = sec.Key("PPROF_DATA_PATH").MustString(path.Join(AppWorkPath, "data/tmp/pprof"))
  651. if !filepath.IsAbs(PprofDataPath) {
  652. PprofDataPath = filepath.Join(AppWorkPath, PprofDataPath)
  653. }
  654. switch sec.Key("LANDING_PAGE").MustString("home") {
  655. case "explore":
  656. LandingPageURL = LandingPageExplore
  657. case "organizations":
  658. LandingPageURL = LandingPageOrganizations
  659. case "login":
  660. LandingPageURL = LandingPageLogin
  661. default:
  662. LandingPageURL = LandingPageHome
  663. }
  664. if len(SSH.Domain) == 0 {
  665. SSH.Domain = Domain
  666. }
  667. SSH.RootPath = path.Join(homeDir, ".ssh")
  668. serverCiphers := sec.Key("SSH_SERVER_CIPHERS").Strings(",")
  669. if len(serverCiphers) > 0 {
  670. SSH.ServerCiphers = serverCiphers
  671. }
  672. serverKeyExchanges := sec.Key("SSH_SERVER_KEY_EXCHANGES").Strings(",")
  673. if len(serverKeyExchanges) > 0 {
  674. SSH.ServerKeyExchanges = serverKeyExchanges
  675. }
  676. serverMACs := sec.Key("SSH_SERVER_MACS").Strings(",")
  677. if len(serverMACs) > 0 {
  678. SSH.ServerMACs = serverMACs
  679. }
  680. SSH.KeyTestPath = os.TempDir()
  681. if err = Cfg.Section("server").MapTo(&SSH); err != nil {
  682. log.Fatal("Failed to map SSH settings: %v", err)
  683. }
  684. for i, key := range SSH.ServerHostKeys {
  685. if !filepath.IsAbs(key) {
  686. SSH.ServerHostKeys[i] = filepath.Join(AppDataPath, key)
  687. }
  688. }
  689. SSH.KeygenPath = sec.Key("SSH_KEYGEN_PATH").MustString("ssh-keygen")
  690. SSH.Port = sec.Key("SSH_PORT").MustInt(22)
  691. SSH.ListenPort = sec.Key("SSH_LISTEN_PORT").MustInt(SSH.Port)
  692. // When disable SSH, start builtin server value is ignored.
  693. if SSH.Disabled {
  694. SSH.StartBuiltinServer = false
  695. }
  696. trustedUserCaKeys := sec.Key("SSH_TRUSTED_USER_CA_KEYS").Strings(",")
  697. for _, caKey := range trustedUserCaKeys {
  698. pubKey, _, _, _, err := gossh.ParseAuthorizedKey([]byte(caKey))
  699. if err != nil {
  700. log.Fatal("Failed to parse TrustedUserCaKeys: %s %v", caKey, err)
  701. }
  702. SSH.TrustedUserCAKeysParsed = append(SSH.TrustedUserCAKeysParsed, pubKey)
  703. }
  704. if len(trustedUserCaKeys) > 0 {
  705. // Set the default as email,username otherwise we can leave it empty
  706. sec.Key("SSH_AUTHORIZED_PRINCIPALS_ALLOW").MustString("username,email")
  707. } else {
  708. sec.Key("SSH_AUTHORIZED_PRINCIPALS_ALLOW").MustString("off")
  709. }
  710. SSH.AuthorizedPrincipalsAllow, SSH.AuthorizedPrincipalsEnabled = parseAuthorizedPrincipalsAllow(sec.Key("SSH_AUTHORIZED_PRINCIPALS_ALLOW").Strings(","))
  711. if !SSH.Disabled && !SSH.StartBuiltinServer {
  712. if err := os.MkdirAll(SSH.RootPath, 0700); err != nil {
  713. log.Fatal("Failed to create '%s': %v", SSH.RootPath, err)
  714. } else if err = os.MkdirAll(SSH.KeyTestPath, 0644); err != nil {
  715. log.Fatal("Failed to create '%s': %v", SSH.KeyTestPath, err)
  716. }
  717. if len(trustedUserCaKeys) > 0 && SSH.AuthorizedPrincipalsEnabled {
  718. fname := sec.Key("SSH_TRUSTED_USER_CA_KEYS_FILENAME").MustString(filepath.Join(SSH.RootPath, "gitea-trusted-user-ca-keys.pem"))
  719. if err := os.WriteFile(fname,
  720. []byte(strings.Join(trustedUserCaKeys, "\n")), 0600); err != nil {
  721. log.Fatal("Failed to create '%s': %v", fname, err)
  722. }
  723. }
  724. }
  725. SSH.MinimumKeySizeCheck = sec.Key("MINIMUM_KEY_SIZE_CHECK").MustBool(SSH.MinimumKeySizeCheck)
  726. minimumKeySizes := Cfg.Section("ssh.minimum_key_sizes").Keys()
  727. for _, key := range minimumKeySizes {
  728. if key.MustInt() != -1 {
  729. SSH.MinimumKeySizes[strings.ToLower(key.Name())] = key.MustInt()
  730. } else {
  731. delete(SSH.MinimumKeySizes, strings.ToLower(key.Name()))
  732. }
  733. }
  734. SSH.AuthorizedKeysBackup = sec.Key("SSH_AUTHORIZED_KEYS_BACKUP").MustBool(true)
  735. SSH.CreateAuthorizedKeysFile = sec.Key("SSH_CREATE_AUTHORIZED_KEYS_FILE").MustBool(true)
  736. SSH.AuthorizedPrincipalsBackup = false
  737. SSH.CreateAuthorizedPrincipalsFile = false
  738. if SSH.AuthorizedPrincipalsEnabled {
  739. SSH.AuthorizedPrincipalsBackup = sec.Key("SSH_AUTHORIZED_PRINCIPALS_BACKUP").MustBool(true)
  740. SSH.CreateAuthorizedPrincipalsFile = sec.Key("SSH_CREATE_AUTHORIZED_PRINCIPALS_FILE").MustBool(true)
  741. }
  742. SSH.ExposeAnonymous = sec.Key("SSH_EXPOSE_ANONYMOUS").MustBool(false)
  743. SSH.AuthorizedKeysCommandTemplate = sec.Key("SSH_AUTHORIZED_KEYS_COMMAND_TEMPLATE").MustString(SSH.AuthorizedKeysCommandTemplate)
  744. SSH.AuthorizedKeysCommandTemplateTemplate = template.Must(template.New("").Parse(SSH.AuthorizedKeysCommandTemplate))
  745. SSH.PerWriteTimeout = sec.Key("SSH_PER_WRITE_TIMEOUT").MustDuration(PerWriteTimeout)
  746. SSH.PerWritePerKbTimeout = sec.Key("SSH_PER_WRITE_PER_KB_TIMEOUT").MustDuration(PerWritePerKbTimeout)
  747. if err = Cfg.Section("oauth2").MapTo(&OAuth2); err != nil {
  748. log.Fatal("Failed to OAuth2 settings: %v", err)
  749. return
  750. }
  751. if !filepath.IsAbs(OAuth2.JWTSigningPrivateKeyFile) {
  752. OAuth2.JWTSigningPrivateKeyFile = filepath.Join(AppDataPath, OAuth2.JWTSigningPrivateKeyFile)
  753. }
  754. sec = Cfg.Section("admin")
  755. Admin.DefaultEmailNotification = sec.Key("DEFAULT_EMAIL_NOTIFICATIONS").MustString("enabled")
  756. sec = Cfg.Section("security")
  757. InstallLock = sec.Key("INSTALL_LOCK").MustBool(false)
  758. SecretKey = sec.Key("SECRET_KEY").MustString("!#@FDEWREWR&*(")
  759. LogInRememberDays = sec.Key("LOGIN_REMEMBER_DAYS").MustInt(7)
  760. CookieUserName = sec.Key("COOKIE_USERNAME").MustString("gitea_awesome")
  761. CookieRememberName = sec.Key("COOKIE_REMEMBER_NAME").MustString("gitea_incredible")
  762. ReverseProxyAuthUser = sec.Key("REVERSE_PROXY_AUTHENTICATION_USER").MustString("X-WEBAUTH-USER")
  763. ReverseProxyAuthEmail = sec.Key("REVERSE_PROXY_AUTHENTICATION_EMAIL").MustString("X-WEBAUTH-EMAIL")
  764. ReverseProxyLimit = sec.Key("REVERSE_PROXY_LIMIT").MustInt(1)
  765. ReverseProxyTrustedProxies = sec.Key("REVERSE_PROXY_TRUSTED_PROXIES").Strings(",")
  766. if len(ReverseProxyTrustedProxies) == 0 {
  767. ReverseProxyTrustedProxies = []string{"127.0.0.0/8", "::1/128"}
  768. }
  769. MinPasswordLength = sec.Key("MIN_PASSWORD_LENGTH").MustInt(6)
  770. ImportLocalPaths = sec.Key("IMPORT_LOCAL_PATHS").MustBool(false)
  771. DisableGitHooks = sec.Key("DISABLE_GIT_HOOKS").MustBool(true)
  772. DisableWebhooks = sec.Key("DISABLE_WEBHOOKS").MustBool(false)
  773. OnlyAllowPushIfGiteaEnvironmentSet = sec.Key("ONLY_ALLOW_PUSH_IF_GITEA_ENVIRONMENT_SET").MustBool(true)
  774. PasswordHashAlgo = sec.Key("PASSWORD_HASH_ALGO").MustString("pbkdf2")
  775. CSRFCookieHTTPOnly = sec.Key("CSRF_COOKIE_HTTP_ONLY").MustBool(true)
  776. PasswordCheckPwn = sec.Key("PASSWORD_CHECK_PWN").MustBool(false)
  777. SuccessfulTokensCacheSize = sec.Key("SUCCESSFUL_TOKENS_CACHE_SIZE").MustInt(20)
  778. InternalToken = loadInternalToken(sec)
  779. cfgdata := sec.Key("PASSWORD_COMPLEXITY").Strings(",")
  780. if len(cfgdata) == 0 {
  781. cfgdata = []string{"off"}
  782. }
  783. PasswordComplexity = make([]string, 0, len(cfgdata))
  784. for _, name := range cfgdata {
  785. name := strings.ToLower(strings.Trim(name, `"`))
  786. if name != "" {
  787. PasswordComplexity = append(PasswordComplexity, name)
  788. }
  789. }
  790. newAttachmentService()
  791. newLFSService()
  792. timeFormatKey := Cfg.Section("time").Key("FORMAT").MustString("")
  793. if timeFormatKey != "" {
  794. TimeFormat = map[string]string{
  795. "ANSIC": time.ANSIC,
  796. "UnixDate": time.UnixDate,
  797. "RubyDate": time.RubyDate,
  798. "RFC822": time.RFC822,
  799. "RFC822Z": time.RFC822Z,
  800. "RFC850": time.RFC850,
  801. "RFC1123": time.RFC1123,
  802. "RFC1123Z": time.RFC1123Z,
  803. "RFC3339": time.RFC3339,
  804. "RFC3339Nano": time.RFC3339Nano,
  805. "Kitchen": time.Kitchen,
  806. "Stamp": time.Stamp,
  807. "StampMilli": time.StampMilli,
  808. "StampMicro": time.StampMicro,
  809. "StampNano": time.StampNano,
  810. }[timeFormatKey]
  811. // When the TimeFormatKey does not exist in the previous map e.g.'2006-01-02 15:04:05'
  812. if len(TimeFormat) == 0 {
  813. TimeFormat = timeFormatKey
  814. TestTimeFormat, _ := time.Parse(TimeFormat, TimeFormat)
  815. if TestTimeFormat.Format(time.RFC3339) != "2006-01-02T15:04:05Z" {
  816. log.Warn("Provided TimeFormat: %s does not create a fully specified date and time.", TimeFormat)
  817. log.Warn("In order to display dates and times correctly please check your time format has 2006, 01, 02, 15, 04 and 05")
  818. }
  819. log.Trace("Custom TimeFormat: %s", TimeFormat)
  820. }
  821. }
  822. zone := Cfg.Section("time").Key("DEFAULT_UI_LOCATION").String()
  823. if zone != "" {
  824. DefaultUILocation, err = time.LoadLocation(zone)
  825. if err != nil {
  826. log.Fatal("Load time zone failed: %v", err)
  827. } else {
  828. log.Info("Default UI Location is %v", zone)
  829. }
  830. }
  831. if DefaultUILocation == nil {
  832. DefaultUILocation = time.Local
  833. }
  834. RunUser = Cfg.Section("").Key("RUN_USER").MustString(user.CurrentUsername())
  835. // The following is a purposefully undocumented option. Please do not run Gitea as root. It will only cause future headaches.
  836. // Please don't use root as a bandaid to "fix" something that is broken, instead the broken thing should instead be fixed properly.
  837. unsafeAllowRunAsRoot := Cfg.Section("").Key("I_AM_BEING_UNSAFE_RUNNING_AS_ROOT").MustBool(false)
  838. RunMode = Cfg.Section("").Key("RUN_MODE").MustString("prod")
  839. IsProd = strings.EqualFold(RunMode, "prod")
  840. // Does not check run user when the install lock is off.
  841. if InstallLock {
  842. currentUser, match := IsRunUserMatchCurrentUser(RunUser)
  843. if !match {
  844. log.Fatal("Expect user '%s' but current user is: %s", RunUser, currentUser)
  845. }
  846. }
  847. // check if we run as root
  848. if os.Getuid() == 0 {
  849. if !unsafeAllowRunAsRoot {
  850. // Special thanks to VLC which inspired the wording of this messaging.
  851. 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")
  852. }
  853. 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.")
  854. }
  855. SSH.BuiltinServerUser = Cfg.Section("server").Key("BUILTIN_SSH_SERVER_USER").MustString(RunUser)
  856. newRepository()
  857. newPictureService()
  858. if err = Cfg.Section("ui").MapTo(&UI); err != nil {
  859. log.Fatal("Failed to map UI settings: %v", err)
  860. } else if err = Cfg.Section("markdown").MapTo(&Markdown); err != nil {
  861. log.Fatal("Failed to map Markdown settings: %v", err)
  862. } else if err = Cfg.Section("admin").MapTo(&Admin); err != nil {
  863. log.Fatal("Fail to map Admin settings: %v", err)
  864. } else if err = Cfg.Section("api").MapTo(&API); err != nil {
  865. log.Fatal("Failed to map API settings: %v", err)
  866. } else if err = Cfg.Section("metrics").MapTo(&Metrics); err != nil {
  867. log.Fatal("Failed to map Metrics settings: %v", err)
  868. }
  869. u := *appURL
  870. u.Path = path.Join(u.Path, "api", "swagger")
  871. API.SwaggerURL = u.String()
  872. newGit()
  873. newMirror()
  874. Langs = Cfg.Section("i18n").Key("LANGS").Strings(",")
  875. if len(Langs) == 0 {
  876. Langs = []string{
  877. "en-US", "zh-CN", "zh-HK", "zh-TW", "de-DE", "fr-FR", "nl-NL", "lv-LV",
  878. "ru-RU", "uk-UA", "ja-JP", "es-ES", "pt-BR", "pt-PT", "pl-PL", "bg-BG",
  879. "it-IT", "fi-FI", "tr-TR", "cs-CZ", "sr-SP", "sv-SE", "ko-KR", "el-GR",
  880. "fa-IR", "hu-HU", "id-ID", "ml-IN"}
  881. }
  882. Names = Cfg.Section("i18n").Key("NAMES").Strings(",")
  883. if len(Names) == 0 {
  884. Names = []string{"English", "简体中文", "繁體中文(香港)", "繁體中文(台灣)", "Deutsch",
  885. "français", "Nederlands", "latviešu", "русский", "Українська", "日本語",
  886. "español", "português do Brasil", "Português de Portugal", "polski", "български",
  887. "italiano", "suomi", "Türkçe", "čeština", "српски", "svenska", "한국어", "ελληνικά",
  888. "فارسی", "magyar nyelv", "bahasa Indonesia", "മലയാളം"}
  889. }
  890. ShowFooterBranding = Cfg.Section("other").Key("SHOW_FOOTER_BRANDING").MustBool(false)
  891. ShowFooterVersion = Cfg.Section("other").Key("SHOW_FOOTER_VERSION").MustBool(true)
  892. ShowFooterTemplateLoadTime = Cfg.Section("other").Key("SHOW_FOOTER_TEMPLATE_LOAD_TIME").MustBool(true)
  893. UI.ShowUserEmail = Cfg.Section("ui").Key("SHOW_USER_EMAIL").MustBool(true)
  894. UI.DefaultShowFullName = Cfg.Section("ui").Key("DEFAULT_SHOW_FULL_NAME").MustBool(false)
  895. UI.SearchRepoDescription = Cfg.Section("ui").Key("SEARCH_REPO_DESCRIPTION").MustBool(true)
  896. UI.UseServiceWorker = Cfg.Section("ui").Key("USE_SERVICE_WORKER").MustBool(true)
  897. HasRobotsTxt, err = util.IsFile(path.Join(CustomPath, "robots.txt"))
  898. if err != nil {
  899. log.Error("Unable to check if %s is a file. Error: %v", path.Join(CustomPath, "robots.txt"), err)
  900. }
  901. newMarkup()
  902. sec = Cfg.Section("U2F")
  903. U2F.TrustedFacets, _ = shellquote.Split(sec.Key("TRUSTED_FACETS").MustString(strings.TrimSuffix(AppURL, AppSubURL+"/")))
  904. U2F.AppID = sec.Key("APP_ID").MustString(strings.TrimSuffix(AppURL, "/"))
  905. UI.ReactionsMap = make(map[string]bool)
  906. for _, reaction := range UI.Reactions {
  907. UI.ReactionsMap[reaction] = true
  908. }
  909. UI.CustomEmojisMap = make(map[string]string)
  910. for _, emoji := range UI.CustomEmojis {
  911. UI.CustomEmojisMap[emoji] = ":" + emoji + ":"
  912. }
  913. }
  914. func parseAuthorizedPrincipalsAllow(values []string) ([]string, bool) {
  915. anything := false
  916. email := false
  917. username := false
  918. for _, value := range values {
  919. v := strings.ToLower(strings.TrimSpace(value))
  920. switch v {
  921. case "off":
  922. return []string{"off"}, false
  923. case "email":
  924. email = true
  925. case "username":
  926. username = true
  927. case "anything":
  928. anything = true
  929. }
  930. }
  931. if anything {
  932. return []string{"anything"}, true
  933. }
  934. authorizedPrincipalsAllow := []string{}
  935. if username {
  936. authorizedPrincipalsAllow = append(authorizedPrincipalsAllow, "username")
  937. }
  938. if email {
  939. authorizedPrincipalsAllow = append(authorizedPrincipalsAllow, "email")
  940. }
  941. return authorizedPrincipalsAllow, true
  942. }
  943. func loadInternalToken(sec *ini.Section) string {
  944. uri := sec.Key("INTERNAL_TOKEN_URI").String()
  945. if len(uri) == 0 {
  946. return loadOrGenerateInternalToken(sec)
  947. }
  948. tempURI, err := url.Parse(uri)
  949. if err != nil {
  950. log.Fatal("Failed to parse INTERNAL_TOKEN_URI (%s): %v", uri, err)
  951. }
  952. switch tempURI.Scheme {
  953. case "file":
  954. fp, err := os.OpenFile(tempURI.RequestURI(), os.O_RDWR, 0600)
  955. if err != nil {
  956. log.Fatal("Failed to open InternalTokenURI (%s): %v", uri, err)
  957. }
  958. defer fp.Close()
  959. buf, err := io.ReadAll(fp)
  960. if err != nil {
  961. log.Fatal("Failed to read InternalTokenURI (%s): %v", uri, err)
  962. }
  963. // No token in the file, generate one and store it.
  964. if len(buf) == 0 {
  965. token, err := generate.NewInternalToken()
  966. if err != nil {
  967. log.Fatal("Error generate internal token: %v", err)
  968. }
  969. if _, err := io.WriteString(fp, token); err != nil {
  970. log.Fatal("Error writing to InternalTokenURI (%s): %v", uri, err)
  971. }
  972. return token
  973. }
  974. return strings.TrimSpace(string(buf))
  975. default:
  976. log.Fatal("Unsupported URI-Scheme %q (INTERNAL_TOKEN_URI = %q)", tempURI.Scheme, uri)
  977. }
  978. return ""
  979. }
  980. func loadOrGenerateInternalToken(sec *ini.Section) string {
  981. var err error
  982. token := sec.Key("INTERNAL_TOKEN").String()
  983. if len(token) == 0 {
  984. token, err = generate.NewInternalToken()
  985. if err != nil {
  986. log.Fatal("Error generate internal token: %v", err)
  987. }
  988. // Save secret
  989. CreateOrAppendToCustomConf(func(cfg *ini.File) {
  990. cfg.Section("security").Key("INTERNAL_TOKEN").SetValue(token)
  991. })
  992. }
  993. return token
  994. }
  995. // MakeAbsoluteAssetURL returns the absolute asset url prefix without a trailing slash
  996. func MakeAbsoluteAssetURL(appURL string, staticURLPrefix string) string {
  997. parsedPrefix, err := url.Parse(strings.TrimSuffix(staticURLPrefix, "/"))
  998. if err != nil {
  999. log.Fatal("Unable to parse STATIC_URL_PREFIX: %v", err)
  1000. }
  1001. if err == nil && parsedPrefix.Hostname() == "" {
  1002. if staticURLPrefix == "" {
  1003. return strings.TrimSuffix(appURL, "/")
  1004. }
  1005. // StaticURLPrefix is just a path
  1006. return util.URLJoin(appURL, strings.TrimSuffix(staticURLPrefix, "/"))
  1007. }
  1008. return strings.TrimSuffix(staticURLPrefix, "/")
  1009. }
  1010. // MakeManifestData generates web app manifest JSON
  1011. func MakeManifestData(appName string, appURL string, absoluteAssetURL string) []byte {
  1012. type manifestIcon struct {
  1013. Src string `json:"src"`
  1014. Type string `json:"type"`
  1015. Sizes string `json:"sizes"`
  1016. }
  1017. type manifestJSON struct {
  1018. Name string `json:"name"`
  1019. ShortName string `json:"short_name"`
  1020. StartURL string `json:"start_url"`
  1021. Icons []manifestIcon `json:"icons"`
  1022. }
  1023. bytes, err := json.Marshal(&manifestJSON{
  1024. Name: appName,
  1025. ShortName: appName,
  1026. StartURL: appURL,
  1027. Icons: []manifestIcon{
  1028. {
  1029. Src: absoluteAssetURL + "/assets/img/logo.png",
  1030. Type: "image/png",
  1031. Sizes: "512x512",
  1032. },
  1033. {
  1034. Src: absoluteAssetURL + "/assets/img/logo.svg",
  1035. Type: "image/svg+xml",
  1036. Sizes: "512x512",
  1037. },
  1038. },
  1039. })
  1040. if err != nil {
  1041. log.Error("unable to marshal manifest JSON. Error: %v", err)
  1042. return make([]byte, 0)
  1043. }
  1044. return bytes
  1045. }
  1046. // CreateOrAppendToCustomConf creates or updates the custom config.
  1047. // Use the callback to set individual values.
  1048. func CreateOrAppendToCustomConf(callback func(cfg *ini.File)) {
  1049. cfg := ini.Empty()
  1050. isFile, err := util.IsFile(CustomConf)
  1051. if err != nil {
  1052. log.Error("Unable to check if %s is a file. Error: %v", CustomConf, err)
  1053. }
  1054. if isFile {
  1055. if err := cfg.Append(CustomConf); err != nil {
  1056. log.Error("failed to load custom conf %s: %v", CustomConf, err)
  1057. return
  1058. }
  1059. }
  1060. callback(cfg)
  1061. if err := os.MkdirAll(filepath.Dir(CustomConf), os.ModePerm); err != nil {
  1062. log.Fatal("failed to create '%s': %v", CustomConf, err)
  1063. return
  1064. }
  1065. if err := cfg.SaveTo(CustomConf); err != nil {
  1066. log.Fatal("error saving to custom config: %v", err)
  1067. }
  1068. // Change permissions to be more restrictive
  1069. fi, err := os.Stat(CustomConf)
  1070. if err != nil {
  1071. log.Error("Failed to determine current conf file permissions: %v", err)
  1072. return
  1073. }
  1074. if fi.Mode().Perm() > 0o600 {
  1075. if err = os.Chmod(CustomConf, 0o600); err != nil {
  1076. log.Warn("Failed changing conf file permissions to -rw-------. Consider changing them manually.")
  1077. }
  1078. }
  1079. }
  1080. // NewServices initializes the services
  1081. func NewServices() {
  1082. InitDBConfig()
  1083. newService()
  1084. newOAuth2Client()
  1085. NewLogServices(false)
  1086. newCacheService()
  1087. newSessionService()
  1088. newCORSService()
  1089. newMailService()
  1090. newRegisterMailService()
  1091. newNotifyMailService()
  1092. newProxyService()
  1093. newWebhookService()
  1094. newMigrationsService()
  1095. newIndexerService()
  1096. newTaskService()
  1097. NewQueueService()
  1098. newProject()
  1099. newMimeTypeMap()
  1100. newFederationService()
  1101. }
  1102. // NewServicesForInstall initializes the services for install
  1103. func NewServicesForInstall() {
  1104. newService()
  1105. newMailService()
  1106. }