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.

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