setting.go 13 KB

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