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.

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