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

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