setting.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package setting
  5. import (
  6. "fmt"
  7. "net/url"
  8. "os"
  9. "os/exec"
  10. "path"
  11. "path/filepath"
  12. "runtime"
  13. "strings"
  14. "time"
  15. "github.com/Unknwon/com"
  16. "github.com/macaron-contrib/oauth2"
  17. "github.com/macaron-contrib/session"
  18. "gopkg.in/ini.v1"
  19. "github.com/gogits/gogs/modules/bindata"
  20. "github.com/gogits/gogs/modules/log"
  21. // "github.com/gogits/gogs/modules/ssh"
  22. )
  23. type Scheme string
  24. const (
  25. HTTP Scheme = "http"
  26. HTTPS Scheme = "https"
  27. FCGI Scheme = "fcgi"
  28. )
  29. type LandingPage string
  30. const (
  31. LANDING_PAGE_HOME LandingPage = "/"
  32. LANDING_PAGE_EXPLORE LandingPage = "/explore"
  33. )
  34. var (
  35. // App settings.
  36. AppVer string
  37. AppName string
  38. AppUrl string
  39. AppSubUrl string
  40. // Server settings.
  41. Protocol Scheme
  42. Domain string
  43. HttpAddr, HttpPort string
  44. DisableSSH bool
  45. SSHPort int
  46. SSHDomain string
  47. OfflineMode bool
  48. DisableRouterLog bool
  49. CertFile, KeyFile string
  50. StaticRootPath string
  51. EnableGzip bool
  52. LandingPageUrl LandingPage
  53. // Security settings.
  54. InstallLock bool
  55. SecretKey string
  56. LogInRememberDays int
  57. CookieUserName string
  58. CookieRememberName string
  59. ReverseProxyAuthUser string
  60. // Database settings.
  61. UseSQLite3 bool
  62. UseMySQL bool
  63. UsePostgreSQL bool
  64. // Webhook settings.
  65. Webhook struct {
  66. TaskInterval int
  67. DeliverTimeout int
  68. SkipTLSVerify bool
  69. }
  70. // Repository settings.
  71. RepoRootPath string
  72. ScriptType string
  73. // UI settings.
  74. IssuePagingNum int
  75. // Picture settings.
  76. PictureService string
  77. AvatarUploadPath string
  78. GravatarSource string
  79. DisableGravatar bool
  80. // Log settings.
  81. LogRootPath string
  82. LogModes []string
  83. LogConfigs []string
  84. // Attachment settings.
  85. AttachmentPath string
  86. AttachmentAllowedTypes string
  87. AttachmentMaxSize int64
  88. AttachmentMaxFiles int
  89. AttachmentEnabled bool
  90. // Time settings.
  91. TimeFormat string
  92. // Cache settings.
  93. CacheAdapter string
  94. CacheInternal int
  95. CacheConn string
  96. EnableRedis bool
  97. EnableMemcache bool
  98. // Session settings.
  99. SessionConfig session.Options
  100. // Git settings.
  101. Git struct {
  102. MaxGitDiffLines int
  103. GcArgs []string `delim:" "`
  104. Fsck struct {
  105. Enable bool
  106. Interval int
  107. Args []string `delim:" "`
  108. } `ini:"git.fsck"`
  109. }
  110. // I18n settings.
  111. Langs, Names []string
  112. // Other settings.
  113. ShowFooterBranding bool
  114. // Global setting objects.
  115. Cfg *ini.File
  116. CustomPath string // Custom directory path.
  117. CustomConf string
  118. ProdMode bool
  119. RunUser string
  120. IsWindows bool
  121. HasRobotsTxt bool
  122. )
  123. func init() {
  124. IsWindows = runtime.GOOS == "windows"
  125. log.NewLogger(0, "console", `{"level": 0}`)
  126. }
  127. func ExecPath() (string, error) {
  128. file, err := exec.LookPath(os.Args[0])
  129. if err != nil {
  130. return "", err
  131. }
  132. p, err := filepath.Abs(file)
  133. if err != nil {
  134. return "", err
  135. }
  136. return p, nil
  137. }
  138. // WorkDir returns absolute path of work directory.
  139. func WorkDir() (string, error) {
  140. execPath, err := ExecPath()
  141. return path.Dir(strings.Replace(execPath, "\\", "/", -1)), err
  142. }
  143. func forcePathSeparator(path string) {
  144. if strings.Contains(path, "\\") {
  145. log.Fatal(4, "Do not use '\\' or '\\\\' in paths, instead, please use '/' in all places")
  146. }
  147. }
  148. // NewConfigContext initializes configuration context.
  149. // NOTE: do not print any log except error.
  150. func NewConfigContext() {
  151. workDir, err := WorkDir()
  152. if err != nil {
  153. log.Fatal(4, "Fail to get work directory: %v", err)
  154. }
  155. Cfg, err = ini.Load(bindata.MustAsset("conf/app.ini"))
  156. if err != nil {
  157. log.Fatal(4, "Fail to parse 'conf/app.ini': %v", err)
  158. }
  159. CustomPath = os.Getenv("GOGS_CUSTOM")
  160. if len(CustomPath) == 0 {
  161. CustomPath = path.Join(workDir, "custom")
  162. }
  163. if len(CustomConf) == 0 {
  164. CustomConf = path.Join(CustomPath, "conf/app.ini")
  165. }
  166. if com.IsFile(CustomConf) {
  167. if err = Cfg.Append(CustomConf); err != nil {
  168. log.Fatal(4, "Fail to load custom conf '%s': %v", CustomConf, err)
  169. }
  170. } else {
  171. log.Warn("Custom config (%s) not found, ignore this if you're running first time", CustomConf)
  172. }
  173. Cfg.NameMapper = ini.AllCapsUnderscore
  174. LogRootPath = Cfg.Section("log").Key("ROOT_PATH").MustString(path.Join(workDir, "log"))
  175. forcePathSeparator(LogRootPath)
  176. sec := Cfg.Section("server")
  177. AppName = Cfg.Section("").Key("APP_NAME").MustString("Gogs: Go Git Service")
  178. AppUrl = sec.Key("ROOT_URL").MustString("http://localhost:3000/")
  179. if AppUrl[len(AppUrl)-1] != '/' {
  180. AppUrl += "/"
  181. }
  182. // Check if has app suburl.
  183. url, err := url.Parse(AppUrl)
  184. if err != nil {
  185. log.Fatal(4, "Invalid ROOT_URL(%s): %s", AppUrl, err)
  186. }
  187. AppSubUrl = strings.TrimSuffix(url.Path, "/")
  188. Protocol = HTTP
  189. if sec.Key("PROTOCOL").String() == "https" {
  190. Protocol = HTTPS
  191. CertFile = sec.Key("CERT_FILE").String()
  192. KeyFile = sec.Key("KEY_FILE").String()
  193. } else if sec.Key("PROTOCOL").String() == "fcgi" {
  194. Protocol = FCGI
  195. }
  196. Domain = sec.Key("DOMAIN").MustString("localhost")
  197. HttpAddr = sec.Key("HTTP_ADDR").MustString("0.0.0.0")
  198. HttpPort = sec.Key("HTTP_PORT").MustString("3000")
  199. DisableSSH = sec.Key("DISABLE_SSH").MustBool()
  200. SSHDomain = sec.Key("SSH_DOMAIN").MustString(Domain)
  201. SSHPort = sec.Key("SSH_PORT").MustInt(22)
  202. OfflineMode = sec.Key("OFFLINE_MODE").MustBool()
  203. DisableRouterLog = sec.Key("DISABLE_ROUTER_LOG").MustBool()
  204. StaticRootPath = sec.Key("STATIC_ROOT_PATH").MustString(workDir)
  205. EnableGzip = sec.Key("ENABLE_GZIP").MustBool()
  206. switch sec.Key("LANDING_PAGE").MustString("home") {
  207. case "explore":
  208. LandingPageUrl = LANDING_PAGE_EXPLORE
  209. default:
  210. LandingPageUrl = LANDING_PAGE_HOME
  211. }
  212. sec = Cfg.Section("security")
  213. InstallLock = sec.Key("INSTALL_LOCK").MustBool()
  214. SecretKey = sec.Key("SECRET_KEY").String()
  215. LogInRememberDays = sec.Key("LOGIN_REMEMBER_DAYS").MustInt()
  216. CookieUserName = sec.Key("COOKIE_USERNAME").String()
  217. CookieRememberName = sec.Key("COOKIE_REMEMBER_NAME").String()
  218. ReverseProxyAuthUser = sec.Key("REVERSE_PROXY_AUTHENTICATION_USER").MustString("X-WEBAUTH-USER")
  219. sec = Cfg.Section("attachment")
  220. AttachmentPath = sec.Key("PATH").MustString("data/attachments")
  221. if !filepath.IsAbs(AttachmentPath) {
  222. AttachmentPath = path.Join(workDir, AttachmentPath)
  223. }
  224. AttachmentAllowedTypes = sec.Key("ALLOWED_TYPES").MustString("image/jpeg|image/png")
  225. AttachmentMaxSize = sec.Key("MAX_SIZE").MustInt64(32)
  226. AttachmentMaxFiles = sec.Key("MAX_FILES").MustInt(10)
  227. AttachmentEnabled = sec.Key("ENABLE").MustBool(true)
  228. TimeFormat = map[string]string{
  229. "ANSIC": time.ANSIC,
  230. "UnixDate": time.UnixDate,
  231. "RubyDate": time.RubyDate,
  232. "RFC822": time.RFC822,
  233. "RFC822Z": time.RFC822Z,
  234. "RFC850": time.RFC850,
  235. "RFC1123": time.RFC1123,
  236. "RFC1123Z": time.RFC1123Z,
  237. "RFC3339": time.RFC3339,
  238. "RFC3339Nano": time.RFC3339Nano,
  239. "Kitchen": time.Kitchen,
  240. "Stamp": time.Stamp,
  241. "StampMilli": time.StampMilli,
  242. "StampMicro": time.StampMicro,
  243. "StampNano": time.StampNano,
  244. }[Cfg.Section("time").Key("FORMAT").MustString("RFC1123")]
  245. RunUser = Cfg.Section("").Key("RUN_USER").String()
  246. curUser := os.Getenv("USER")
  247. if len(curUser) == 0 {
  248. curUser = os.Getenv("USERNAME")
  249. }
  250. // Does not check run user when the install lock is off.
  251. if InstallLock && RunUser != curUser {
  252. log.Fatal(4, "Expect user(%s) but current user is: %s", RunUser, curUser)
  253. }
  254. // Determine and create root git repository path.
  255. homeDir, err := com.HomeDir()
  256. if err != nil {
  257. log.Fatal(4, "Fail to get home directory: %v", err)
  258. }
  259. homeDir = strings.Replace(homeDir, "\\", "/", -1)
  260. sec = Cfg.Section("repository")
  261. RepoRootPath = sec.Key("ROOT").MustString(path.Join(homeDir, "gogs-repositories"))
  262. forcePathSeparator(RepoRootPath)
  263. if !filepath.IsAbs(RepoRootPath) {
  264. RepoRootPath = path.Join(workDir, RepoRootPath)
  265. } else {
  266. RepoRootPath = path.Clean(RepoRootPath)
  267. }
  268. ScriptType = sec.Key("SCRIPT_TYPE").MustString("bash")
  269. // UI settings.
  270. IssuePagingNum = Cfg.Section("ui").Key("ISSUE_PAGING_NUM").MustInt(10)
  271. sec = Cfg.Section("picture")
  272. PictureService = sec.Key("SERVICE").In("server", []string{"server"})
  273. AvatarUploadPath = sec.Key("AVATAR_UPLOAD_PATH").MustString("data/avatars")
  274. forcePathSeparator(AvatarUploadPath)
  275. if !filepath.IsAbs(AvatarUploadPath) {
  276. AvatarUploadPath = path.Join(workDir, AvatarUploadPath)
  277. }
  278. switch sec.Key("GRAVATAR_SOURCE").MustString("gravatar") {
  279. case "duoshuo":
  280. GravatarSource = "http://gravatar.duoshuo.com/avatar/"
  281. default:
  282. GravatarSource = "//1.gravatar.com/avatar/"
  283. }
  284. DisableGravatar = sec.Key("DISABLE_GRAVATAR").MustBool()
  285. if OfflineMode {
  286. DisableGravatar = true
  287. }
  288. if err = Cfg.Section("git").MapTo(&Git); err != nil {
  289. log.Fatal(4, "Fail to map Git settings: %v", err)
  290. }
  291. Langs = Cfg.Section("i18n").Key("LANGS").Strings(",")
  292. Names = Cfg.Section("i18n").Key("NAMES").Strings(",")
  293. ShowFooterBranding = Cfg.Section("other").Key("SHOW_FOOTER_BRANDING").MustBool()
  294. HasRobotsTxt = com.IsFile(path.Join(CustomPath, "robots.txt"))
  295. }
  296. var Service struct {
  297. ActiveCodeLives int
  298. ResetPwdCodeLives int
  299. RegisterEmailConfirm bool
  300. DisableRegistration bool
  301. ShowRegistrationButton bool
  302. RequireSignInView bool
  303. EnableCacheAvatar bool
  304. EnableNotifyMail bool
  305. EnableReverseProxyAuth bool
  306. EnableReverseProxyAutoRegister bool
  307. DisableMinimumKeySizeCheck bool
  308. }
  309. func newService() {
  310. sec := Cfg.Section("service")
  311. Service.ActiveCodeLives = sec.Key("ACTIVE_CODE_LIVE_MINUTES").MustInt(180)
  312. Service.ResetPwdCodeLives = sec.Key("RESET_PASSWD_CODE_LIVE_MINUTES").MustInt(180)
  313. Service.DisableRegistration = sec.Key("DISABLE_REGISTRATION").MustBool()
  314. Service.ShowRegistrationButton = sec.Key("SHOW_REGISTRATION_BUTTON").MustBool(!Service.DisableRegistration)
  315. Service.RequireSignInView = sec.Key("REQUIRE_SIGNIN_VIEW").MustBool()
  316. Service.EnableCacheAvatar = sec.Key("ENABLE_CACHE_AVATAR").MustBool()
  317. Service.EnableReverseProxyAuth = sec.Key("ENABLE_REVERSE_PROXY_AUTHENTICATION").MustBool()
  318. Service.EnableReverseProxyAutoRegister = sec.Key("ENABLE_REVERSE_PROXY_AUTO_REGISTRATION").MustBool()
  319. Service.DisableMinimumKeySizeCheck = sec.Key("DISABLE_MINIMUM_KEY_SIZE_CHECK").MustBool()
  320. }
  321. var logLevels = map[string]string{
  322. "Trace": "0",
  323. "Debug": "1",
  324. "Info": "2",
  325. "Warn": "3",
  326. "Error": "4",
  327. "Critical": "5",
  328. }
  329. func newLogService() {
  330. log.Info("%s %s", AppName, AppVer)
  331. // Get and check log mode.
  332. LogModes = strings.Split(Cfg.Section("log").Key("MODE").MustString("console"), ",")
  333. LogConfigs = make([]string, len(LogModes))
  334. for i, mode := range LogModes {
  335. mode = strings.TrimSpace(mode)
  336. sec, err := Cfg.GetSection("log." + mode)
  337. if err != nil {
  338. log.Fatal(4, "Unknown log mode: %s", mode)
  339. }
  340. validLevels := []string{"Trace", "Debug", "Info", "Warn", "Error", "Critical"}
  341. // Log level.
  342. levelName := Cfg.Section("log."+mode).Key("LEVEL").In(
  343. Cfg.Section("log").Key("LEVEL").In("Trace", validLevels),
  344. validLevels)
  345. level, ok := logLevels[levelName]
  346. if !ok {
  347. log.Fatal(4, "Unknown log level: %s", levelName)
  348. }
  349. // Generate log configuration.
  350. switch mode {
  351. case "console":
  352. LogConfigs[i] = fmt.Sprintf(`{"level":%s}`, level)
  353. case "file":
  354. logPath := sec.Key("FILE_NAME").MustString(path.Join(LogRootPath, "gogs.log"))
  355. os.MkdirAll(path.Dir(logPath), os.ModePerm)
  356. LogConfigs[i] = fmt.Sprintf(
  357. `{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`, level,
  358. logPath,
  359. sec.Key("LOG_ROTATE").MustBool(true),
  360. sec.Key("MAX_LINES").MustInt(1000000),
  361. 1<<uint(sec.Key("MAX_SIZE_SHIFT").MustInt(28)),
  362. sec.Key("DAILY_ROTATE").MustBool(true),
  363. sec.Key("MAX_DAYS").MustInt(7))
  364. case "conn":
  365. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level,
  366. sec.Key("RECONNECT_ON_MSG").MustBool(),
  367. sec.Key("RECONNECT").MustBool(),
  368. sec.Key("PROTOCOL").In("tcp", []string{"tcp", "unix", "udp"}),
  369. sec.Key("ADDR").MustString(":7020"))
  370. case "smtp":
  371. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"username":"%s","password":"%s","host":"%s","sendTos":"%s","subject":"%s"}`, level,
  372. sec.Key("USER").MustString("example@example.com"),
  373. sec.Key("PASSWD").MustString("******"),
  374. sec.Key("HOST").MustString("127.0.0.1:25"),
  375. sec.Key("RECEIVERS").MustString("[]"),
  376. sec.Key("SUBJECT").MustString("Diagnostic message from serve"))
  377. case "database":
  378. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"driver":"%s","conn":"%s"}`, level,
  379. sec.Key("DRIVER").String(),
  380. sec.Key("CONN").String())
  381. }
  382. log.NewLogger(Cfg.Section("log").Key("BUFFER_LEN").MustInt64(10000), mode, LogConfigs[i])
  383. log.Info("Log Mode: %s(%s)", strings.Title(mode), levelName)
  384. }
  385. }
  386. func newCacheService() {
  387. CacheAdapter = Cfg.Section("cache").Key("ADAPTER").In("memory", []string{"memory", "redis", "memcache"})
  388. if EnableRedis {
  389. log.Info("Redis Enabled")
  390. }
  391. if EnableMemcache {
  392. log.Info("Memcache Enabled")
  393. }
  394. switch CacheAdapter {
  395. case "memory":
  396. CacheInternal = Cfg.Section("cache").Key("INTERVAL").MustInt(60)
  397. case "redis", "memcache":
  398. CacheConn = strings.Trim(Cfg.Section("cache").Key("HOST").String(), "\" ")
  399. default:
  400. log.Fatal(4, "Unknown cache adapter: %s", CacheAdapter)
  401. }
  402. log.Info("Cache Service Enabled")
  403. }
  404. func newSessionService() {
  405. SessionConfig.Provider = Cfg.Section("session").Key("PROVIDER").In("memory",
  406. []string{"memory", "file", "redis", "mysql"})
  407. SessionConfig.ProviderConfig = strings.Trim(Cfg.Section("session").Key("PROVIDER_CONFIG").String(), "\" ")
  408. SessionConfig.CookieName = Cfg.Section("session").Key("COOKIE_NAME").MustString("i_like_gogits")
  409. SessionConfig.CookiePath = AppSubUrl
  410. SessionConfig.Secure = Cfg.Section("session").Key("COOKIE_SECURE").MustBool()
  411. SessionConfig.Gclifetime = Cfg.Section("session").Key("GC_INTERVAL_TIME").MustInt64(86400)
  412. SessionConfig.Maxlifetime = Cfg.Section("session").Key("SESSION_LIFE_TIME").MustInt64(86400)
  413. log.Info("Session Service Enabled")
  414. }
  415. // Mailer represents mail service.
  416. type Mailer struct {
  417. Name string
  418. Host string
  419. From string
  420. User, Passwd string
  421. DisableHelo bool
  422. HeloHostname string
  423. SkipVerify bool
  424. UseCertificate bool
  425. CertFile, KeyFile string
  426. }
  427. type OauthInfo struct {
  428. oauth2.Options
  429. AuthUrl, TokenUrl string
  430. }
  431. // Oauther represents oauth service.
  432. type Oauther struct {
  433. GitHub, Google, Tencent,
  434. Twitter, Weibo bool
  435. OauthInfos map[string]*OauthInfo
  436. }
  437. var (
  438. MailService *Mailer
  439. OauthService *Oauther
  440. )
  441. func newMailService() {
  442. sec := Cfg.Section("mailer")
  443. // Check mailer setting.
  444. if !sec.Key("ENABLED").MustBool() {
  445. return
  446. }
  447. MailService = &Mailer{
  448. Name: sec.Key("NAME").MustString(AppName),
  449. Host: sec.Key("HOST").String(),
  450. User: sec.Key("USER").String(),
  451. Passwd: sec.Key("PASSWD").String(),
  452. DisableHelo: sec.Key("DISABLE_HELO").MustBool(),
  453. HeloHostname: sec.Key("HELO_HOSTNAME").String(),
  454. SkipVerify: sec.Key("SKIP_VERIFY").MustBool(),
  455. UseCertificate: sec.Key("USE_CERTIFICATE").MustBool(),
  456. CertFile: sec.Key("CERT_FILE").String(),
  457. KeyFile: sec.Key("KEY_FILE").String(),
  458. }
  459. MailService.From = sec.Key("FROM").MustString(MailService.User)
  460. log.Info("Mail Service Enabled")
  461. }
  462. func newRegisterMailService() {
  463. if !Cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").MustBool() {
  464. return
  465. } else if MailService == nil {
  466. log.Warn("Register Mail Service: Mail Service is not enabled")
  467. return
  468. }
  469. Service.RegisterEmailConfirm = true
  470. log.Info("Register Mail Service Enabled")
  471. }
  472. func newNotifyMailService() {
  473. if !Cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").MustBool() {
  474. return
  475. } else if MailService == nil {
  476. log.Warn("Notify Mail Service: Mail Service is not enabled")
  477. return
  478. }
  479. Service.EnableNotifyMail = true
  480. log.Info("Notify Mail Service Enabled")
  481. }
  482. func newWebhookService() {
  483. sec := Cfg.Section("webhook")
  484. Webhook.TaskInterval = sec.Key("TASK_INTERVAL").MustInt(1)
  485. Webhook.DeliverTimeout = sec.Key("DELIVER_TIMEOUT").MustInt(5)
  486. Webhook.SkipTLSVerify = sec.Key("SKIP_TLS_VERIFY").MustBool()
  487. }
  488. func NewServices() {
  489. newService()
  490. newLogService()
  491. newCacheService()
  492. newSessionService()
  493. newMailService()
  494. newRegisterMailService()
  495. newNotifyMailService()
  496. newWebhookService()
  497. // ssh.Listen("2222")
  498. }