setting.go 13 KB

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