setting.go 15 KB

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