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.

530 lines
15 KiB

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