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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  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. EnableGitHooks bool
  246. }
  247. func newService() {
  248. Service.ActiveCodeLives = Cfg.MustInt("service", "ACTIVE_CODE_LIVE_MINUTES", 180)
  249. Service.ResetPwdCodeLives = Cfg.MustInt("service", "RESET_PASSWD_CODE_LIVE_MINUTES", 180)
  250. Service.DisableRegistration = Cfg.MustBool("service", "DISABLE_REGISTRATION")
  251. Service.RequireSignInView = Cfg.MustBool("service", "REQUIRE_SIGNIN_VIEW")
  252. Service.EnableCacheAvatar = Cfg.MustBool("service", "ENABLE_CACHE_AVATAR")
  253. Service.EnableReverseProxyAuth = Cfg.MustBool("service", "ENABLE_REVERSE_PROXY_AUTHENTICATION")
  254. Service.EnableGitHooks = Cfg.MustBool("service", "ENABLE_GIT_HOOKS")
  255. }
  256. var logLevels = map[string]string{
  257. "Trace": "0",
  258. "Debug": "1",
  259. "Info": "2",
  260. "Warn": "3",
  261. "Error": "4",
  262. "Critical": "5",
  263. }
  264. func newLogService() {
  265. log.Info("%s %s", AppName, AppVer)
  266. // Get and check log mode.
  267. LogModes = strings.Split(Cfg.MustValue("log", "MODE", "console"), ",")
  268. LogConfigs = make([]string, len(LogModes))
  269. for i, mode := range LogModes {
  270. mode = strings.TrimSpace(mode)
  271. modeSec := "log." + mode
  272. if _, err := Cfg.GetSection(modeSec); err != nil {
  273. log.Fatal(4, "Unknown log mode: %s", mode)
  274. }
  275. // Log level.
  276. levelName := Cfg.MustValueRange("log."+mode, "LEVEL", "Trace",
  277. []string{"Trace", "Debug", "Info", "Warn", "Error", "Critical"})
  278. level, ok := logLevels[levelName]
  279. if !ok {
  280. log.Fatal(4, "Unknown log level: %s", levelName)
  281. }
  282. // Generate log configuration.
  283. switch mode {
  284. case "console":
  285. LogConfigs[i] = fmt.Sprintf(`{"level":%s}`, level)
  286. case "file":
  287. logPath := Cfg.MustValue(modeSec, "FILE_NAME", path.Join(LogRootPath, "gogs.log"))
  288. os.MkdirAll(path.Dir(logPath), os.ModePerm)
  289. LogConfigs[i] = fmt.Sprintf(
  290. `{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`, level,
  291. logPath,
  292. Cfg.MustBool(modeSec, "LOG_ROTATE", true),
  293. Cfg.MustInt(modeSec, "MAX_LINES", 1000000),
  294. 1<<uint(Cfg.MustInt(modeSec, "MAX_SIZE_SHIFT", 28)),
  295. Cfg.MustBool(modeSec, "DAILY_ROTATE", true),
  296. Cfg.MustInt(modeSec, "MAX_DAYS", 7))
  297. case "conn":
  298. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level,
  299. Cfg.MustBool(modeSec, "RECONNECT_ON_MSG"),
  300. Cfg.MustBool(modeSec, "RECONNECT"),
  301. Cfg.MustValueRange(modeSec, "PROTOCOL", "tcp", []string{"tcp", "unix", "udp"}),
  302. Cfg.MustValue(modeSec, "ADDR", ":7020"))
  303. case "smtp":
  304. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"username":"%s","password":"%s","host":"%s","sendTos":"%s","subject":"%s"}`, level,
  305. Cfg.MustValue(modeSec, "USER", "example@example.com"),
  306. Cfg.MustValue(modeSec, "PASSWD", "******"),
  307. Cfg.MustValue(modeSec, "HOST", "127.0.0.1:25"),
  308. Cfg.MustValue(modeSec, "RECEIVERS", "[]"),
  309. Cfg.MustValue(modeSec, "SUBJECT", "Diagnostic message from serve"))
  310. case "database":
  311. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"driver":"%s","conn":"%s"}`, level,
  312. Cfg.MustValue(modeSec, "DRIVER"),
  313. Cfg.MustValue(modeSec, "CONN"))
  314. }
  315. log.NewLogger(Cfg.MustInt64("log", "BUFFER_LEN", 10000), mode, LogConfigs[i])
  316. log.Info("Log Mode: %s(%s)", strings.Title(mode), levelName)
  317. }
  318. }
  319. func newCacheService() {
  320. CacheAdapter = Cfg.MustValueRange("cache", "ADAPTER", "memory", []string{"memory", "redis", "memcache"})
  321. if EnableRedis {
  322. log.Info("Redis Enabled")
  323. }
  324. if EnableMemcache {
  325. log.Info("Memcache Enabled")
  326. }
  327. switch CacheAdapter {
  328. case "memory":
  329. CacheInternal = Cfg.MustInt("cache", "INTERVAL", 60)
  330. case "redis", "memcache":
  331. CacheConn = strings.Trim(Cfg.MustValue("cache", "HOST"), "\" ")
  332. default:
  333. log.Fatal(4, "Unknown cache adapter: %s", CacheAdapter)
  334. }
  335. log.Info("Cache Service Enabled")
  336. }
  337. func newSessionService() {
  338. SessionProvider = Cfg.MustValueRange("session", "PROVIDER", "memory",
  339. []string{"memory", "file", "redis", "mysql"})
  340. SessionConfig = new(session.Config)
  341. SessionConfig.ProviderConfig = strings.Trim(Cfg.MustValue("session", "PROVIDER_CONFIG"), "\" ")
  342. SessionConfig.CookieName = Cfg.MustValue("session", "COOKIE_NAME", "i_like_gogits")
  343. SessionConfig.CookiePath = AppSubUrl
  344. SessionConfig.Secure = Cfg.MustBool("session", "COOKIE_SECURE")
  345. SessionConfig.EnableSetCookie = Cfg.MustBool("session", "ENABLE_SET_COOKIE", true)
  346. SessionConfig.Gclifetime = Cfg.MustInt64("session", "GC_INTERVAL_TIME", 86400)
  347. SessionConfig.Maxlifetime = Cfg.MustInt64("session", "SESSION_LIFE_TIME", 86400)
  348. if SessionProvider == "file" {
  349. os.MkdirAll(path.Dir(SessionConfig.ProviderConfig), os.ModePerm)
  350. }
  351. log.Info("Session Service Enabled")
  352. }
  353. // Mailer represents mail service.
  354. type Mailer struct {
  355. Name string
  356. Host string
  357. From string
  358. User, Passwd string
  359. }
  360. type OauthInfo struct {
  361. ClientId, ClientSecret string
  362. Scopes string
  363. AuthUrl, TokenUrl string
  364. }
  365. // Oauther represents oauth service.
  366. type Oauther struct {
  367. GitHub, Google, Tencent,
  368. Twitter, Weibo bool
  369. OauthInfos map[string]*OauthInfo
  370. }
  371. var (
  372. MailService *Mailer
  373. OauthService *Oauther
  374. )
  375. func newMailService() {
  376. // Check mailer setting.
  377. if !Cfg.MustBool("mailer", "ENABLED") {
  378. return
  379. }
  380. MailService = &Mailer{
  381. Name: Cfg.MustValue("mailer", "NAME", AppName),
  382. Host: Cfg.MustValue("mailer", "HOST"),
  383. User: Cfg.MustValue("mailer", "USER"),
  384. Passwd: Cfg.MustValue("mailer", "PASSWD"),
  385. }
  386. MailService.From = Cfg.MustValue("mailer", "FROM", MailService.User)
  387. log.Info("Mail Service Enabled")
  388. }
  389. func newRegisterMailService() {
  390. if !Cfg.MustBool("service", "REGISTER_EMAIL_CONFIRM") {
  391. return
  392. } else if MailService == nil {
  393. log.Warn("Register Mail Service: Mail Service is not enabled")
  394. return
  395. }
  396. Service.RegisterEmailConfirm = true
  397. log.Info("Register Mail Service Enabled")
  398. }
  399. func newNotifyMailService() {
  400. if !Cfg.MustBool("service", "ENABLE_NOTIFY_MAIL") {
  401. return
  402. } else if MailService == nil {
  403. log.Warn("Notify Mail Service: Mail Service is not enabled")
  404. return
  405. }
  406. Service.EnableNotifyMail = true
  407. log.Info("Notify Mail Service Enabled")
  408. }
  409. func newWebhookService() {
  410. WebhookTaskInterval = Cfg.MustInt("webhook", "TASK_INTERVAL", 1)
  411. WebhookDeliverTimeout = Cfg.MustInt("webhook", "DELIVER_TIMEOUT", 5)
  412. }
  413. func NewServices() {
  414. newService()
  415. newLogService()
  416. newCacheService()
  417. newSessionService()
  418. newMailService()
  419. newRegisterMailService()
  420. newNotifyMailService()
  421. newWebhookService()
  422. // ssh.Listen("2022")
  423. }