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

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