tool.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  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 base
  5. import (
  6. "crypto/hmac"
  7. "crypto/md5"
  8. "crypto/rand"
  9. "crypto/sha1"
  10. "encoding/base64"
  11. "encoding/hex"
  12. "errors"
  13. "fmt"
  14. "hash"
  15. "html/template"
  16. "math"
  17. "regexp"
  18. "strings"
  19. "time"
  20. "github.com/Unknwon/com"
  21. "github.com/Unknwon/i18n"
  22. "github.com/gogits/gogs/modules/avatar"
  23. "github.com/gogits/gogs/modules/setting"
  24. )
  25. // Encode string to md5 hex value.
  26. func EncodeMd5(str string) string {
  27. m := md5.New()
  28. m.Write([]byte(str))
  29. return hex.EncodeToString(m.Sum(nil))
  30. }
  31. // Encode string to sha1 hex value.
  32. func EncodeSha1(str string) string {
  33. h := sha1.New()
  34. h.Write([]byte(str))
  35. return hex.EncodeToString(h.Sum(nil))
  36. }
  37. func BasicAuthDecode(encoded string) (user string, name string, err error) {
  38. var s []byte
  39. s, err = base64.StdEncoding.DecodeString(encoded)
  40. if err != nil {
  41. return user, name, err
  42. }
  43. auth := strings.SplitN(string(s), ":", 2)
  44. return auth[0], auth[1], err
  45. }
  46. func BasicAuthEncode(username, password string) string {
  47. return base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
  48. }
  49. // GetRandomString generate random string by specify chars.
  50. func GetRandomString(n int, alphabets ...byte) string {
  51. const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  52. var bytes = make([]byte, n)
  53. rand.Read(bytes)
  54. for i, b := range bytes {
  55. if len(alphabets) == 0 {
  56. bytes[i] = alphanum[b%byte(len(alphanum))]
  57. } else {
  58. bytes[i] = alphabets[b%byte(len(alphabets))]
  59. }
  60. }
  61. return string(bytes)
  62. }
  63. // http://code.google.com/p/go/source/browse/pbkdf2/pbkdf2.go?repo=crypto
  64. func PBKDF2(password, salt []byte, iter, keyLen int, h func() hash.Hash) []byte {
  65. prf := hmac.New(h, password)
  66. hashLen := prf.Size()
  67. numBlocks := (keyLen + hashLen - 1) / hashLen
  68. var buf [4]byte
  69. dk := make([]byte, 0, numBlocks*hashLen)
  70. U := make([]byte, hashLen)
  71. for block := 1; block <= numBlocks; block++ {
  72. // N.B.: || means concatenation, ^ means XOR
  73. // for each block T_i = U_1 ^ U_2 ^ ... ^ U_iter
  74. // U_1 = PRF(password, salt || uint(i))
  75. prf.Reset()
  76. prf.Write(salt)
  77. buf[0] = byte(block >> 24)
  78. buf[1] = byte(block >> 16)
  79. buf[2] = byte(block >> 8)
  80. buf[3] = byte(block)
  81. prf.Write(buf[:4])
  82. dk = prf.Sum(dk)
  83. T := dk[len(dk)-hashLen:]
  84. copy(U, T)
  85. // U_n = PRF(password, U_(n-1))
  86. for n := 2; n <= iter; n++ {
  87. prf.Reset()
  88. prf.Write(U)
  89. U = U[:0]
  90. U = prf.Sum(U)
  91. for x := range U {
  92. T[x] ^= U[x]
  93. }
  94. }
  95. }
  96. return dk[:keyLen]
  97. }
  98. // verify time limit code
  99. func VerifyTimeLimitCode(data string, minutes int, code string) bool {
  100. if len(code) <= 18 {
  101. return false
  102. }
  103. // split code
  104. start := code[:12]
  105. lives := code[12:18]
  106. if d, err := com.StrTo(lives).Int(); err == nil {
  107. minutes = d
  108. }
  109. // right active code
  110. retCode := CreateTimeLimitCode(data, minutes, start)
  111. if retCode == code && minutes > 0 {
  112. // check time is expired or not
  113. before, _ := DateParse(start, "YmdHi")
  114. now := time.Now()
  115. if before.Add(time.Minute*time.Duration(minutes)).Unix() > now.Unix() {
  116. return true
  117. }
  118. }
  119. return false
  120. }
  121. const TimeLimitCodeLength = 12 + 6 + 40
  122. // create a time limit code
  123. // code format: 12 length date time string + 6 minutes string + 40 sha1 encoded string
  124. func CreateTimeLimitCode(data string, minutes int, startInf interface{}) string {
  125. format := "YmdHi"
  126. var start, end time.Time
  127. var startStr, endStr string
  128. if startInf == nil {
  129. // Use now time create code
  130. start = time.Now()
  131. startStr = DateFormat(start, format)
  132. } else {
  133. // use start string create code
  134. startStr = startInf.(string)
  135. start, _ = DateParse(startStr, format)
  136. startStr = DateFormat(start, format)
  137. }
  138. end = start.Add(time.Minute * time.Duration(minutes))
  139. endStr = DateFormat(end, format)
  140. // create sha1 encode string
  141. sh := sha1.New()
  142. sh.Write([]byte(data + setting.SecretKey + startStr + endStr + com.ToStr(minutes)))
  143. encoded := hex.EncodeToString(sh.Sum(nil))
  144. code := fmt.Sprintf("%s%06d%s", startStr, minutes, encoded)
  145. return code
  146. }
  147. // AvatarLink returns avatar link by given e-mail.
  148. func AvatarLink(email string) string {
  149. if setting.DisableGravatar {
  150. return setting.AppSubUrl + "/img/avatar_default.jpg"
  151. }
  152. gravatarHash := avatar.HashEmail(email)
  153. if setting.Service.EnableCacheAvatar {
  154. return setting.AppSubUrl + "/avatar/" + gravatarHash
  155. }
  156. return setting.GravatarSource + gravatarHash
  157. }
  158. // Seconds-based time units
  159. const (
  160. Minute = 60
  161. Hour = 60 * Minute
  162. Day = 24 * Hour
  163. Week = 7 * Day
  164. Month = 30 * Day
  165. Year = 12 * Month
  166. )
  167. func computeTimeDiff(diff int64) (int64, string) {
  168. diffStr := ""
  169. switch {
  170. case diff <= 0:
  171. diff = 0
  172. diffStr = "now"
  173. case diff < 2:
  174. diff = 0
  175. diffStr = "1 second"
  176. case diff < 1*Minute:
  177. diffStr = fmt.Sprintf("%d seconds", diff)
  178. diff = 0
  179. case diff < 2*Minute:
  180. diff -= 1 * Minute
  181. diffStr = "1 minute"
  182. case diff < 1*Hour:
  183. diffStr = fmt.Sprintf("%d minutes", diff/Minute)
  184. diff -= diff / Minute * Minute
  185. case diff < 2*Hour:
  186. diff -= 1 * Hour
  187. diffStr = "1 hour"
  188. case diff < 1*Day:
  189. diffStr = fmt.Sprintf("%d hours", diff/Hour)
  190. diff -= diff / Hour * Hour
  191. case diff < 2*Day:
  192. diff -= 1 * Day
  193. diffStr = "1 day"
  194. case diff < 1*Week:
  195. diffStr = fmt.Sprintf("%d days", diff/Day)
  196. diff -= diff / Day * Day
  197. case diff < 2*Week:
  198. diff -= 1 * Week
  199. diffStr = "1 week"
  200. case diff < 1*Month:
  201. diffStr = fmt.Sprintf("%d weeks", diff/Week)
  202. diff -= diff / Week * Week
  203. case diff < 2*Month:
  204. diff -= 1 * Month
  205. diffStr = "1 month"
  206. case diff < 1*Year:
  207. diffStr = fmt.Sprintf("%d months", diff/Month)
  208. diff -= diff / Month * Month
  209. case diff < 2*Year:
  210. diff -= 1 * Year
  211. diffStr = "1 year"
  212. default:
  213. diffStr = fmt.Sprintf("%d years", diff/Year)
  214. diff = 0
  215. }
  216. return diff, diffStr
  217. }
  218. // TimeSincePro calculates the time interval and generate full user-friendly string.
  219. func TimeSincePro(then time.Time) string {
  220. now := time.Now()
  221. diff := now.Unix() - then.Unix()
  222. if then.After(now) {
  223. return "future"
  224. }
  225. var timeStr, diffStr string
  226. for {
  227. if diff == 0 {
  228. break
  229. }
  230. diff, diffStr = computeTimeDiff(diff)
  231. timeStr += ", " + diffStr
  232. }
  233. return strings.TrimPrefix(timeStr, ", ")
  234. }
  235. func timeSince(then time.Time, lang string) string {
  236. now := time.Now()
  237. lbl := i18n.Tr(lang, "tool.ago")
  238. diff := now.Unix() - then.Unix()
  239. if then.After(now) {
  240. lbl = i18n.Tr(lang, "tool.from_now")
  241. diff = then.Unix() - now.Unix()
  242. }
  243. switch {
  244. case diff <= 0:
  245. return i18n.Tr(lang, "tool.now")
  246. case diff <= 2:
  247. return i18n.Tr(lang, "tool.1s", lbl)
  248. case diff < 1*Minute:
  249. return i18n.Tr(lang, "tool.seconds", diff, lbl)
  250. case diff < 2*Minute:
  251. return i18n.Tr(lang, "tool.1m", lbl)
  252. case diff < 1*Hour:
  253. return i18n.Tr(lang, "tool.minutes", diff/Minute, lbl)
  254. case diff < 2*Hour:
  255. return i18n.Tr(lang, "tool.1h", lbl)
  256. case diff < 1*Day:
  257. return i18n.Tr(lang, "tool.hours", diff/Hour, lbl)
  258. case diff < 2*Day:
  259. return i18n.Tr(lang, "tool.1d", lbl)
  260. case diff < 1*Week:
  261. return i18n.Tr(lang, "tool.days", diff/Day, lbl)
  262. case diff < 2*Week:
  263. return i18n.Tr(lang, "tool.1w", lbl)
  264. case diff < 1*Month:
  265. return i18n.Tr(lang, "tool.weeks", diff/Week, lbl)
  266. case diff < 2*Month:
  267. return i18n.Tr(lang, "tool.1mon", lbl)
  268. case diff < 1*Year:
  269. return i18n.Tr(lang, "tool.months", diff/Month, lbl)
  270. case diff < 2*Year:
  271. return i18n.Tr(lang, "tool.1y", lbl)
  272. default:
  273. return i18n.Tr(lang, "tool.years", diff/Year, lbl)
  274. }
  275. }
  276. // TimeSince calculates the time interval and generate user-friendly string.
  277. func TimeSince(t time.Time, lang string) template.HTML {
  278. return template.HTML(fmt.Sprintf(`<span class="time-since" title="%s">%s</span>`, t.Format(setting.TimeFormat), timeSince(t, lang)))
  279. }
  280. const (
  281. Byte = 1
  282. KByte = Byte * 1024
  283. MByte = KByte * 1024
  284. GByte = MByte * 1024
  285. TByte = GByte * 1024
  286. PByte = TByte * 1024
  287. EByte = PByte * 1024
  288. )
  289. var bytesSizeTable = map[string]uint64{
  290. "b": Byte,
  291. "kb": KByte,
  292. "mb": MByte,
  293. "gb": GByte,
  294. "tb": TByte,
  295. "pb": PByte,
  296. "eb": EByte,
  297. }
  298. func logn(n, b float64) float64 {
  299. return math.Log(n) / math.Log(b)
  300. }
  301. func humanateBytes(s uint64, base float64, sizes []string) string {
  302. if s < 10 {
  303. return fmt.Sprintf("%dB", s)
  304. }
  305. e := math.Floor(logn(float64(s), base))
  306. suffix := sizes[int(e)]
  307. val := float64(s) / math.Pow(base, math.Floor(e))
  308. f := "%.0f"
  309. if val < 10 {
  310. f = "%.1f"
  311. }
  312. return fmt.Sprintf(f+"%s", val, suffix)
  313. }
  314. // FileSize calculates the file size and generate user-friendly string.
  315. func FileSize(s int64) string {
  316. sizes := []string{"B", "KB", "MB", "GB", "TB", "PB", "EB"}
  317. return humanateBytes(uint64(s), 1024, sizes)
  318. }
  319. // Subtract deals with subtraction of all types of number.
  320. func Subtract(left interface{}, right interface{}) interface{} {
  321. var rleft, rright int64
  322. var fleft, fright float64
  323. var isInt bool = true
  324. switch left.(type) {
  325. case int:
  326. rleft = int64(left.(int))
  327. case int8:
  328. rleft = int64(left.(int8))
  329. case int16:
  330. rleft = int64(left.(int16))
  331. case int32:
  332. rleft = int64(left.(int32))
  333. case int64:
  334. rleft = left.(int64)
  335. case float32:
  336. fleft = float64(left.(float32))
  337. isInt = false
  338. case float64:
  339. fleft = left.(float64)
  340. isInt = false
  341. }
  342. switch right.(type) {
  343. case int:
  344. rright = int64(right.(int))
  345. case int8:
  346. rright = int64(right.(int8))
  347. case int16:
  348. rright = int64(right.(int16))
  349. case int32:
  350. rright = int64(right.(int32))
  351. case int64:
  352. rright = right.(int64)
  353. case float32:
  354. fright = float64(left.(float32))
  355. isInt = false
  356. case float64:
  357. fleft = left.(float64)
  358. isInt = false
  359. }
  360. if isInt {
  361. return rleft - rright
  362. } else {
  363. return fleft + float64(rleft) - (fright + float64(rright))
  364. }
  365. }
  366. // DateFormat pattern rules.
  367. var datePatterns = []string{
  368. // year
  369. "Y", "2006", // A full numeric representation of a year, 4 digits Examples: 1999 or 2003
  370. "y", "06", //A two digit representation of a year Examples: 99 or 03
  371. // month
  372. "m", "01", // Numeric representation of a month, with leading zeros 01 through 12
  373. "n", "1", // Numeric representation of a month, without leading zeros 1 through 12
  374. "M", "Jan", // A short textual representation of a month, three letters Jan through Dec
  375. "F", "January", // A full textual representation of a month, such as January or March January through December
  376. // day
  377. "d", "02", // Day of the month, 2 digits with leading zeros 01 to 31
  378. "j", "2", // Day of the month without leading zeros 1 to 31
  379. // week
  380. "D", "Mon", // A textual representation of a day, three letters Mon through Sun
  381. "l", "Monday", // A full textual representation of the day of the week Sunday through Saturday
  382. // time
  383. "g", "3", // 12-hour format of an hour without leading zeros 1 through 12
  384. "G", "15", // 24-hour format of an hour without leading zeros 0 through 23
  385. "h", "03", // 12-hour format of an hour with leading zeros 01 through 12
  386. "H", "15", // 24-hour format of an hour with leading zeros 00 through 23
  387. "a", "pm", // Lowercase Ante meridiem and Post meridiem am or pm
  388. "A", "PM", // Uppercase Ante meridiem and Post meridiem AM or PM
  389. "i", "04", // Minutes with leading zeros 00 to 59
  390. "s", "05", // Seconds, with leading zeros 00 through 59
  391. // time zone
  392. "T", "MST",
  393. "P", "-07:00",
  394. "O", "-0700",
  395. // RFC 2822
  396. "r", time.RFC1123Z,
  397. }
  398. // Parse Date use PHP time format.
  399. func DateParse(dateString, format string) (time.Time, error) {
  400. replacer := strings.NewReplacer(datePatterns...)
  401. format = replacer.Replace(format)
  402. return time.ParseInLocation(format, dateString, time.Local)
  403. }
  404. // Date takes a PHP like date func to Go's time format.
  405. func DateFormat(t time.Time, format string) string {
  406. replacer := strings.NewReplacer(datePatterns...)
  407. format = replacer.Replace(format)
  408. return t.Format(format)
  409. }
  410. type xssFilter struct {
  411. reg *regexp.Regexp
  412. repl []byte
  413. }
  414. var (
  415. whiteSpace = []byte(" ")
  416. xssFilters = []xssFilter{
  417. {regexp.MustCompile(`\ [ONon]\w*=["]*`), whiteSpace},
  418. {regexp.MustCompile(`<[SCRIPTscript]{6}`), whiteSpace},
  419. {regexp.MustCompile(`=[` + "`" + `'"]*[JAVASCRIPTjavascript \t\0&#x0D;]*:`), whiteSpace},
  420. }
  421. )
  422. // XSS goes through all the XSS filters to make user input content as safe as possible.
  423. func XSS(in []byte) []byte {
  424. for _, filter := range xssFilters {
  425. in = filter.reg.ReplaceAll(in, filter.repl)
  426. }
  427. return in
  428. }
  429. func XSSString(in string) string {
  430. return string(XSS([]byte(in)))
  431. }